阶段六:完成全量架构、兼容退场和注释收口
This commit is contained in:
1 parent
5241a07e47
commit
5f8d999ab0
47 files changed
+7897
-7563
No files matched your search
+39
-27
@@ -25,7 +25,7 @@ import (
|
||||
"xianyu-go/internal/logsafe"
|
||||
)
|
||||
|
||||
// main 封装main业务协调。
|
||||
// main 是验证 CLI 的进程入口;参数与运行错误统一由 run 返回退出码。
|
||||
func main() {
|
||||
// cleanup 用于本次流程后续判断的cleanup
|
||||
var cleanup func() error
|
||||
@@ -100,33 +100,10 @@ func main() {
|
||||
userID := adminUser.ID
|
||||
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
|
||||
|
||||
// 2) 保存 cookie(dialectUpsert: ON CONFLICT/ON DUPLICATE KEY)
|
||||
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
|
||||
fail("❌ 保存 cookie 失败: %v\n", err)
|
||||
// verifyCookieAndSettings 校验跨方言 Cookie 与设置的 upsert 语义,失败时由 CLI 统一清理临时数据。
|
||||
if err := verifyCookieAndSettings(ctx, store, accountID, userID); err != nil {
|
||||
fail("❌ %v\n", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
|
||||
fail("❌ 禁用验证账号失败: %v\n", err)
|
||||
}
|
||||
// 再 Save 一次验证 upsert
|
||||
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
|
||||
fail("❌ 二次保存 cookie 失败: %v\n", err)
|
||||
}
|
||||
// v 用于本次流程后续判断的v
|
||||
v, _ := store.Cookies.GetValue(ctx, accountID)
|
||||
// fingerprint 是 Cookie 的不可逆校验指纹,仅用于验证 upsert 结果。
|
||||
fingerprint := sha256.Sum256([]byte(v))
|
||||
fmt.Printf("✅ cookie upsert 成功,length=%d fingerprint=%x\n", len(v), fingerprint[:8])
|
||||
|
||||
// 3) 系统设置 upsert(dialectUpsert + key 保留字引用)
|
||||
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
|
||||
fail("❌ 系统设置 Set 失败: %v\n", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
|
||||
fail("❌ 系统设置二次 Set 失败: %v\n", err)
|
||||
}
|
||||
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
|
||||
|
||||
// 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE)
|
||||
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
|
||||
@@ -222,6 +199,41 @@ func main() {
|
||||
fmt.Println("\n🎉 全部验证通过")
|
||||
}
|
||||
|
||||
// verifyCookieAndSettings 验证 Cookie 状态写入、重复 upsert 和保留字设置项的跨方言行为。
|
||||
func verifyCookieAndSettings(ctx context.Context, store *db.Store, accountID string, userID int64) error {
|
||||
// firstCookie 是首次保存的非敏感测试 Cookie;secondCookie 用于确认重复保存会覆盖同一账号记录。
|
||||
const firstCookie = "unb=123; _m_h5_tk=tk_1;"
|
||||
// secondCookie 是第二次 upsert 使用的测试凭证,用于验证已存在账号记录会被安全覆盖。
|
||||
const secondCookie = "unb=123; _m_h5_tk=tk_2;"
|
||||
// err 保存首次 Cookie 写入失败原因,调用方据此输出脱敏诊断并执行清理。
|
||||
if err := store.Cookies.Save(ctx, accountID, firstCookie, userID); err != nil {
|
||||
return fmt.Errorf("保存 cookie 失败: %w", err)
|
||||
}
|
||||
// err 保存账号状态写入失败原因,状态记录必须与 Cookie 记录一并跨方言验证。
|
||||
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
|
||||
return fmt.Errorf("禁用验证账号失败: %w", err)
|
||||
}
|
||||
// err 保存覆盖式 Cookie 写入失败原因,失败表示方言 upsert 语义不满足验证要求。
|
||||
if err := store.Cookies.Save(ctx, accountID, secondCookie, userID); err != nil {
|
||||
return fmt.Errorf("二次保存 cookie 失败: %w", err)
|
||||
}
|
||||
// savedCookie 是读取回来的值;fingerprint 仅输出不可逆摘要,避免验证日志泄露完整 Cookie。
|
||||
savedCookie, _ := store.Cookies.GetValue(ctx, accountID)
|
||||
// fingerprint 是读取结果的不可逆摘要,只用于确认更新结果且不得输出完整 Cookie。
|
||||
fingerprint := sha256.Sum256([]byte(savedCookie))
|
||||
fmt.Printf("✅ cookie upsert 成功,length=%d fingerprint=%x\n", len(savedCookie), fingerprint[:8])
|
||||
// err 保存首次设置写入失败原因,数据库方言必须正确处理 key 保留字。
|
||||
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
|
||||
return fmt.Errorf("系统设置 Set 失败: %w", err)
|
||||
}
|
||||
// err 保存第二次设置写入失败原因,用于确认相同键会执行更新而非重复插入。
|
||||
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
|
||||
return fmt.Errorf("系统设置二次 Set 失败: %w", err)
|
||||
}
|
||||
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// safeDiagnosticArgs 将错误参数转换为脱敏文本,避免验证工具把连接凭证写到终端。
|
||||
func safeDiagnosticArgs(args []any) []any {
|
||||
// safeArgs 保存经过错误脱敏的格式化参数;非错误参数保持原有类型和格式语义。
|
||||
|
||||
@@ -43,9 +43,9 @@ shared,feature adapter 直接转换领域 DTO 为 feature-owned UI model。
|
||||
| 3. 生命周期、Engine 和 Automation 重新验收 | 已完成 | 已完成后台任务 owner/Context/Cancel/Wait 收口、同步凭证更新的调用 Context 传递、浏览器组合根生命周期接入和 AST 生命周期门禁;最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||
| 4. React Feature 化和异步状态修复 | 已完成 | 已完成领域契约直接模块、feature API adapter 边界、统一 ApiError、items 地图迁移、定位取消/超时、批量轮询代次隔离、严格 TypeScript 检查和嵌入产物重建;最终证据见 `refactoring-progress.md`。 |
|
||||
| 5. DB 与事务治理重新验收 | 已完成 | 已以 AST 门禁收束上层裸 SQL、Store.DB 与事务入口,补齐订单/商品 UoW 的提交和回滚证据,并完成 SQLite、MySQL、PostgreSQL 与 dbverify 实测;最终提交绑定见 `refactoring-progress.md`。 |
|
||||
| 6. 全量架构、兼容退场和注释收口 | 当前阶段 | 门禁规则已在基础验证层预建;本阶段只激活最终质量规则、清零违规并完成兼容和注释退场。 |
|
||||
| 6. 全量架构、兼容退场和注释收口 | 已完成 | 最终质量门禁已清零;超大文件和过长函数按业务职责拆分,兼容、依赖方向、注释与复杂度门禁保持 fail-closed。最终提交与完整证据见 `refactoring-progress.md`。 |
|
||||
|
||||
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。阶段四已完成,阶段五是唯一允许继续执行的阶段;阶段六不得提前执行。
|
||||
顺序固定为 1 -> 2 -> 3 -> 4 -> 5 -> 6。阶段一是治理建立前的既有基线例外;从阶段二开始,每阶段必须有唯一最终中文提交和完整原始命令输出。六个正式阶段均已完成,阶段二至阶段六的全部门禁永久保持 fail-closed。
|
||||
|
||||
## 阶段一:稳定性、安全和启动生命周期
|
||||
|
||||
@@ -182,7 +182,7 @@ git diff --check
|
||||
PostgreSQL 多方言回归及两个 `cmd/dbverify` 均已实际通过,完整命令输出和提交绑定记录在
|
||||
`refactoring-progress.md`。
|
||||
|
||||
## 阶段六:全量架构、兼容退场和注释收口
|
||||
## 阶段六:全量架构、兼容退场和注释收口(已完成)
|
||||
|
||||
门禁框架和全部阶段规则已经前置建立,本阶段不得重新发明或补写基础规则。本阶段激活最终质量门禁,
|
||||
处理此前各阶段持续开启的全部边界,并清零 service locator、动态 import、前端依赖方向、根级 services
|
||||
@@ -208,6 +208,11 @@ git diff --check
|
||||
适用时还运行浏览器集成、MySQL/PostgreSQL 和两个 cmd/dbverify 命令。最终提交:阶段六:完成全量架构、
|
||||
兼容退场和注释收口。
|
||||
|
||||
完成结论:质量门禁已在不新增白名单、baseline 或忽略目录的前提下清零。组合根、adapter、browser
|
||||
生命周期、DB repository、Engine、通知、续期、Server DTO、二维码、协议和门禁源码均按业务职责拆分;
|
||||
受保护的 CAPTCHA 文件和规范未改动。完整原始验收输出、覆盖率、浏览器集成与多数据库环境例外记录在
|
||||
`refactoring-progress.md`。
|
||||
|
||||
## 执行纪律
|
||||
|
||||
1. 开始一个阶段前,只允许读取总计划状态表并审查当前工作树;不得根据旧阶段编号或已落地代码跳阶段。
|
||||
|
||||
@@ -213,7 +213,73 @@ $ make comments && go vet ./... && make lint && go run ./tools/architecturecheck
|
||||
commentlint: 通过;golangci-lint: 0 issues;architecturecheck: 通过;其余命令退出码 0。
|
||||
```
|
||||
|
||||
## 下一阶段入口
|
||||
## 阶段六:全量架构、兼容退场和注释收口
|
||||
|
||||
阶段五已完成,阶段六:全量架构、兼容退场和注释收口为唯一当前阶段。开始前必须先运行
|
||||
`go run ./tools/architecturecheck`,使已完成阶段的一至五门禁和新激活的质量门禁同时 fail-closed;不得修改冻结 CAPTCHA,也不得把 `frontend/coverage/` 纳入提交。
|
||||
- 最终提交绑定:本文件随唯一最终中文提交 `阶段六:完成全量架构、兼容退场和注释收口` 一并进入 `HEAD`。
|
||||
- 交付范围:质量门禁保持 800 行生产文件、180 行函数和分支复杂度阈值,不新增白名单、baseline、忽略目录或告警降级。组合根、adapter、browser 生命周期、数据库 repository、Engine、通知、续期、二维码、WebSocket、Server DTO 与 architecturecheck 均按业务职责拆分到同包文件;兼容、动态依赖、前端边界和低层依赖扫描继续 fail-closed。
|
||||
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范;二维码确认逻辑仅作同包职责搬移,未改变验证码调用顺序、参数、超时或结果语义。
|
||||
|
||||
### 强制验收原始输出
|
||||
|
||||
```text
|
||||
$ go test ./... -count=1
|
||||
所有测试包通过;其中 internal/engine 38.065s、internal/server 26.716s、internal/xianyu/mtop 28.841s。
|
||||
|
||||
$ go vet ./...
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ make lint
|
||||
golangci-lint run ./...
|
||||
0 issues.
|
||||
|
||||
$ make comments
|
||||
Go 与前端 commentlint 均通过,无缺少中文注释或模板化注释。
|
||||
|
||||
$ go run ./tools/architecturecheck
|
||||
architecturecheck: 通过
|
||||
|
||||
$ go test -race ./internal/server ./internal/engine ./internal/automation
|
||||
ok xianyu-go/internal/server 256.282s
|
||||
ok xianyu-go/internal/engine 308.756s
|
||||
ok xianyu-go/internal/automation 168.737s
|
||||
|
||||
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
|
||||
ok xianyu-go/internal/browser 52.866s
|
||||
|
||||
$ npm test --prefix frontend
|
||||
Test Files 67 passed (67)
|
||||
Tests 402 passed (402)
|
||||
|
||||
$ npm run typecheck --prefix frontend
|
||||
(无输出,退出码 0)
|
||||
|
||||
$ npm run comments:check --prefix frontend
|
||||
commentlint: 通过(无缺少中文注释或模板化注释)
|
||||
|
||||
$ npm run build --prefix frontend
|
||||
vite v6.4.3 building for production...
|
||||
✓ built in 5.13s
|
||||
|
||||
$ make cover
|
||||
total: (statements) 65.9%
|
||||
|
||||
$ make cover-frontend
|
||||
Statements : 79.82% (3704/4640)
|
||||
Lines : 82.17% (3236/3938)
|
||||
|
||||
$ make build && git diff --check
|
||||
go build ./cmd/server
|
||||
(无输出,退出码 0)
|
||||
```
|
||||
|
||||
### 验收边界
|
||||
|
||||
- 覆盖率:Go statements 65.9%;前端 V8 statements 79.82%、lines 82.17%。`cover.out` 与 `frontend/coverage/` 均为生成验证产物,未纳入提交。
|
||||
- 浏览器:已使用 `RUN_BROWSER_INTEGRATION=1` 运行本地 Chromium 集成测试;未调用真实账号或外部平台。
|
||||
- 多数据库:本次环境未配置 `TEST_MYSQL_URL` 和/或 `TEST_POSTGRES_URL`,因此 `make test-multidb` 与两个 `cmd/dbverify` 未执行;阶段五既有 MySQL/PostgreSQL 实测证据保持有效,当前不伪造外部连接结果。
|
||||
- 冻结 CAPTCHA:直接受保护实现、测试和规范均未出现在最终差异中。
|
||||
- 生成物:`npm run build --prefix frontend` 已执行;当前构建输入未导致 `internal/webui/static` 内容变化,未手工修改嵌入产物。
|
||||
|
||||
## 后续维护
|
||||
|
||||
六个正式阶段均已完成。之后的功能变更必须保持全部架构门禁永久 fail-closed,不得恢复阶段状态、扩大兼容白名单、修改注释 baseline 或将覆盖率生成物纳入提交。
|
||||
@@ -7,10 +7,8 @@ package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -21,13 +19,10 @@ import (
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
@@ -231,764 +226,3 @@ func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// Xianyu echoes messages sent by this account back over the same WS. Those
|
||||
// sends are already captured by HandleOutgoingChatMessage; recording the
|
||||
// echo as incoming would put our own bubble on the buyer side and duplicate it.
|
||||
// selfID 保存当前账号从 Cookie 解析出的平台用户标识,用于过滤同账号 WebSocket 回显。
|
||||
if selfID := protocol.TransCookies(message.CookieStr)["unb"]; selfID != "" &&
|
||||
strings.TrimSuffix(strings.TrimSpace(message.SenderUserID), "@goofish") == strings.TrimSuffix(strings.TrimSpace(selfID), "@goofish") {
|
||||
a.logger.Info("忽略账号自身发送的聊天回显", "account", message.AccountID, "chat_id", message.ChatID, "sender_id", message.SenderUserID)
|
||||
return nil
|
||||
}
|
||||
// stored、inserted、err 保存落库消息、是否首次插入及持久化错误。
|
||||
stored, inserted, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
|
||||
BuyerName: message.SenderName, Text: message.Text, MessageID: message.MessageID, ItemID: message.ItemID, Raw: message.Raw,
|
||||
})
|
||||
if stored != nil {
|
||||
a.logger.Info("实时聊天消息已入库", "account", message.AccountID, "chat_id", message.ChatID,
|
||||
"message_key", stored.MessageKey, "message_type", stored.MessageType, "inserted", inserted)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleOutgoingChatMessage records successful manual/automatic text sends as
|
||||
// a side channel; it never participates in platform delivery.
|
||||
// HandleOutgoingChatMessage 处理Outgoing聊天消息。
|
||||
func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.OutgoingChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.chat.RecordOutgoingSent(ctx, db.ChatSession{CookieID: message.AccountID, ChatID: message.ChatID,
|
||||
BuyerID: message.BuyerID}, message.MessageKey, message.Text)
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleMessageRead 接收平台出站消息已读回执,并把非敏感已读状态更新委托给聊天服务。
|
||||
func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// message、err 保存按平台消息键更新的出站消息及持久化错误,以便缺键时回退会话最近消息。
|
||||
message, err := a.chat.MarkOutgoingRead(ctx, event.AccountID, event.MessageID, event.ReadAt)
|
||||
if errors.Is(err, db.ErrNotFound) && event.ChatID != "" {
|
||||
message, err = a.chat.MarkLatestOutgoingRead(ctx, event.AccountID, event.ChatID, event.ReadAt)
|
||||
}
|
||||
if err == nil && message != nil {
|
||||
a.logger.Info("聊天出站消息已标记已读", "account", event.AccountID, "chat_id", event.ChatID,
|
||||
"message_id", event.MessageID, "message_key", message.MessageKey, "read_status", message.ReadStatus)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
// OnAccountAlert 封装On账号Alert业务协调。
|
||||
func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) {
|
||||
a.OnAccountEvent(ctx, cookieID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
|
||||
// OnAccountEvent 把带类型的账号事件转发给通知器。
|
||||
func (a *Adapter) OnAccountEvent(_ context.Context, cookieID, eventType, level, title, body string) {
|
||||
if a.notifier == nil {
|
||||
a.logger.Warn("账号事件通知未发送:通知器未注入", "account", cookieID, "event_type", eventType, "level", level, "title", title)
|
||||
return
|
||||
}
|
||||
if // n、ok 用于本次流程后续判断的n、ok
|
||||
n, ok := a.notifier.(notifyEventNotifier); ok {
|
||||
n.NotifyAccountEvent(cookieID, eventType, level, title, body)
|
||||
return
|
||||
}
|
||||
a.notifier.NotifyAccountAlert(cookieID, level, title, body)
|
||||
}
|
||||
|
||||
// classifyAccountAlertEvent 封装classify账号AlertEvent业务协调。
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
strings.Contains(msg, "滑块"), strings.Contains(msg, "captcha"),
|
||||
strings.Contains(msg, "risk"), strings.Contains(msg, "x5sec"):
|
||||
return engine.EventSecurityVerification
|
||||
case strings.Contains(msg, "禁用"), strings.Contains(msg, "disabled"):
|
||||
return engine.EventAccountDisabled
|
||||
case strings.Contains(msg, "掉线"), strings.Contains(msg, "离线"),
|
||||
strings.Contains(msg, "offline"), strings.Contains(msg, "session"),
|
||||
strings.Contains(msg, "登录凭证已失效"):
|
||||
return engine.EventAccountOffline
|
||||
case strings.Contains(msg, "token"), strings.Contains(msg, "续期"), strings.Contains(msg, "renew"):
|
||||
return engine.EventTokenRenewal
|
||||
default:
|
||||
return engine.EventSystemError
|
||||
}
|
||||
}
|
||||
|
||||
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL, deviceID string) (*mtop.RefreshResult, bool) {
|
||||
// start 用于本次流程后续判断的开始
|
||||
start := time.Now()
|
||||
// logID 用于本次流程后续判断的logID
|
||||
var logID int64
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
if // id、err 用于本次流程后续判断的id、err
|
||||
id, err := a.store.RiskLogs.Add(ctx, db.RiskControlLog{
|
||||
CookieID: cookieID,
|
||||
EventType: "slider_captcha",
|
||||
EventDescription: "触发场景: Token刷新, URL: " + verificationURL,
|
||||
ProcessingStatus: "processing",
|
||||
}); err == nil {
|
||||
logID = id
|
||||
} else {
|
||||
a.logger.Warn("记录风控日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// showBrowser 用于本次流程后续判断的show浏览器
|
||||
showBrowser := false
|
||||
// metadataJSON 用于本次流程后续判断的metadataJSON
|
||||
metadataJSON := ""
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法保存", "账号存储未初始化,无法保存验证后的 Cookie。")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if // d、err 用于本次流程后续判断的d、err
|
||||
d, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID); err == nil {
|
||||
showBrowser = d.ShowBrowser
|
||||
metadataJSON = d.MetadataJSON
|
||||
}
|
||||
|
||||
// provider 用于本次流程后续判断的provider
|
||||
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
|
||||
if a.captchaReq == nil {
|
||||
return "", false, "", nil
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.captchaReq.RequestFreshCaptchaURLContext(runCtx, currentCookies, deviceID)
|
||||
if err != nil || res == nil {
|
||||
return "", false, "", err
|
||||
}
|
||||
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
// newCookies 用于本次流程后续判断的newCookies
|
||||
newCookies := ""
|
||||
// captchaEngine 用于本次流程后续判断的captchaEngine
|
||||
captchaEngine := "playwright"
|
||||
// remoteHandled 用于本次流程后续判断的remoteHandled
|
||||
remoteHandled := false
|
||||
// captchaHeadless 用于本次流程后续判断的captchaHeadless
|
||||
captchaHeadless := browser.ResolveHeadless(showBrowser)
|
||||
// err 用于本次流程后续判断的err
|
||||
var err error
|
||||
if // remoteConfig 用于本次流程后续判断的remote配置
|
||||
remoteConfig := a.loadRemoteCaptchaConfig(ctx, cookieID); remoteConfig != nil {
|
||||
newCookies, remoteHandled, err = solveRemoteCaptcha(
|
||||
ctx, newRemoteCaptchaHTTPClient(), *remoteConfig,
|
||||
cookieID, verificationURL, cookieStr, deviceID, provider,
|
||||
)
|
||||
if remoteHandled {
|
||||
captchaEngine = "remote"
|
||||
} else if err != nil {
|
||||
a.logger.Warn("远程过滑块不可用,回退本机逻辑", "account", cookieID, "err", err)
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
if !remoteHandled {
|
||||
// br、ok 用于本次流程后续判断的br、ok
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "远程服务不可用且浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return nil, false
|
||||
}
|
||||
if // withEngine、ok 用于本次流程后续判断的withEngine、ok
|
||||
withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
} else {
|
||||
newCookies, err = br.TokenCaptchaRecover(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
// manualURL 用于本次流程后续判断的manualURL
|
||||
manualURL := browser.TokenCaptchaManualVerificationURL(err)
|
||||
if strings.TrimSpace(manualURL) == "" {
|
||||
manualURL = verificationURL
|
||||
}
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", logsafe.Error(err), "verification_url", logsafe.URL(manualURL))
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "failed",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块处理失败,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证失败", err.Error())
|
||||
return nil, false
|
||||
}
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
// cookieSnapshot 用于本次流程后续判断的登录凭证Snapshot
|
||||
var cookieSnapshot []cookierefresh.BrowserCookie
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
snapshotComplete := false
|
||||
if !remoteHandled {
|
||||
if // reader、ok 用于本次流程后续判断的reader、ok
|
||||
reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
// profileCookies、profileSnapshot、readErr 用于本次流程后续判断的profileCookies、profileSnapshot、readErr
|
||||
profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
|
||||
if readErr != nil {
|
||||
a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
|
||||
} else {
|
||||
cookieSnapshot = cookierefresh.NormalizeSnapshot(profileSnapshot)
|
||||
if cookieSnapshot == nil {
|
||||
cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
snapshotComplete = true
|
||||
newCookies = profileCookies
|
||||
}
|
||||
}
|
||||
}
|
||||
if !snapshotComplete {
|
||||
if // existing、complete 用于本次流程后续判断的existing、complete
|
||||
existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
|
||||
snapshotComplete = true
|
||||
}
|
||||
}
|
||||
// updatedMetadata 用于本次流程后续判断的updatedMetadata
|
||||
updatedMetadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshotComplete {
|
||||
updatedMetadata = cookierefresh.MetadataWithSnapshot(metadataJSON, cookieSnapshot)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, updatedMetadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "error",
|
||||
ProcessingResult: "滑块完成但保存 Cookie 失败",
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "success",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块验证成功(%s),已更新登录凭证,耗时: %.2f秒", captchaEngine, time.Since(start).Seconds()),
|
||||
CaptchaEngine: captchaEngine,
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
|
||||
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
|
||||
return &mtop.RefreshResult{
|
||||
UpdatedCookies: newCookies,
|
||||
CookieSnapshot: cookieSnapshot,
|
||||
CookieSnapshotComplete: snapshotComplete,
|
||||
CookieStateChanged: newCookies != cookieStr || snapshotComplete,
|
||||
}, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) error {
|
||||
if a.automation == nil {
|
||||
return nil
|
||||
}
|
||||
a.logger.Info("系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
|
||||
// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
// FetchOrderDetail 封装Fetch订单Detail业务协调。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
|
||||
if // detail、ok 用于本次流程后续判断的detail、ok
|
||||
detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
// detail、err 用于本次流程后续判断的detail、err
|
||||
detail, err := a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
if err == nil || !mtop.IsSessionExpiredErr(err) {
|
||||
return detail, err
|
||||
}
|
||||
a.logger.Warn("订单详情检测到 Session 过期,开始即时续期", "account", cookieID, "order_id", orderID)
|
||||
if !a.OnPasswordLoginRefresh(ctx, cookieID) {
|
||||
return nil, fmt.Errorf("订单详情 Session 过期且即时续期失败: %w", err)
|
||||
}
|
||||
a.logger.Info("Cookie 即时续期成功,重新请求订单详情", "account", cookieID, "order_id", orderID)
|
||||
return a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
}
|
||||
|
||||
// fetchOrderDetailAttempt 封装fetch订单Detail尝试次数业务协调。
|
||||
func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID string) (*automation.OrderDetail, error) {
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
defer a.orderFetchMu.Unlock()
|
||||
// 等锁期间其他流程可能已经补齐订单,再检查一次。
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if // remain 用于本次流程后续判断的remain
|
||||
remain := 3*time.Second - time.Since(a.lastOrderFetch); !a.lastOrderFetch.IsZero() && remain > 0 {
|
||||
// timer 用于本次流程后续判断的定时器
|
||||
timer := time.NewTimer(remain)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
a.lastOrderFetch = time.Now()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := a.store.LockAccountCredentials(cookieID)
|
||||
// credentialLocked 标识当前调用是否持有账号凭证锁。
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 只包含订单 MTOP 请求所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(platformData.Value) == "" && !hasCompleteCookieSnapshot(platformData.MetadataJSON) {
|
||||
return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
|
||||
}
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := platformData.Value
|
||||
// requestCtx 用于本次流程后续判断的请求Ctx
|
||||
var requestCtx context.Context
|
||||
// cookieSession 用于本次流程后续判断的登录凭证会话
|
||||
var cookieSession *mtop.CookieSession
|
||||
if // snapshot、complete 用于本次流程后续判断的snapshot、complete
|
||||
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(platformData.MetadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
// 账号凭证快照已读取完成;慢速 MTOP 请求不得继续持有共享凭证锁。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
// detail、fetchErr 用于本次流程后续判断的detail、fetchErr
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
// authoritativeCookies、authoritativeSnapshot、sessionChanged 用于本次流程后续判断的authoritativeCookies、authoritativeSnapshot、sessionChanged
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
// credentialUnlock 保存重新进入凭证提交临界区的释放函数。
|
||||
credentialUnlock = a.store.LockAccountCredentials(cookieID)
|
||||
credentialLocked = true
|
||||
// latestPlatformData 和 reloadErr 保存外部调用完成后的最新凭证快照及重读错误。
|
||||
latestPlatformData, reloadErr := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
|
||||
if reloadErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("重读订单账号最新 Cookie: %w", reloadErr))
|
||||
} else if latestPlatformData.Value != platformData.Value || latestPlatformData.MetadataJSON != platformData.MetadataJSON {
|
||||
// 凭证在外部调用期间已被其他流程更新,丢弃旧快照响应,避免覆盖更新后的状态。
|
||||
sessionChanged = false
|
||||
authoritativeSnapshot = nil
|
||||
} else if sessionChanged {
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(latestPlatformData.MetadataJSON, authoritativeSnapshot)
|
||||
}
|
||||
if // persistErr 用于本次流程后续判断的persistErr
|
||||
persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
}
|
||||
if fetchErr != nil {
|
||||
return nil, fetchErr
|
||||
}
|
||||
if detail == nil {
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if reloadErr == nil && latestPlatformData.Value == platformData.Value && latestPlatformData.MetadataJSON == platformData.MetadataJSON && !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
// 外部调用产生的凭证结果已处理完成,释放短暂提交临界区。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
Amount: detail.Amount, OrderStatus: detail.OrderStatus,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// wakeCredentialBlockedAutomation 封装wakeCredentialBlocked自动化业务协调。
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.credentialWake == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.credentialWake.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// hasCompleteCookieSnapshot 封装hasComplete登录凭证Snapshot业务协调。
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
// ok 用于本次流程后续判断的ok
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
|
||||
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
|
||||
// order、err 用于本次流程后续判断的order、err
|
||||
order, err := a.store.Orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
return nil, false
|
||||
}
|
||||
if order.Amount == "" || order.Quantity == "" || order.SpecName == "" || order.SpecValue == "" {
|
||||
return nil, false
|
||||
}
|
||||
return &automation.OrderDetail{
|
||||
Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue,
|
||||
Amount: order.Amount, OrderStatus: order.OrderStatus,
|
||||
}, true
|
||||
}
|
||||
|
||||
// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
|
||||
// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
|
||||
// OnPasswordLoginRefresh 封装On密码登录Refresh业务协调。
|
||||
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
|
||||
// cooldown 用于本次流程后续判断的cooldown
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if // ok、remain、reason 用于本次流程后续判断的ok、remain、reason
|
||||
ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
|
||||
a.logger.Warn("协议续期冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
// primary 标识当前调用是否负责执行协议续期;后到调用方只等待其结果。
|
||||
if primary := a.beginPasswordRenewalResult(cookieID); !primary {
|
||||
a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID)
|
||||
return a.waitPasswordRenewalResult(ctx, cookieID)
|
||||
}
|
||||
// sharedRenewed 保存首次调用的最终恢复结果,并在所有返回路径唤醒等待者。
|
||||
sharedRenewed := false
|
||||
defer func() { a.finishPasswordRenewalResult(cookieID, sharedRenewed) }()
|
||||
// platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。
|
||||
var platformData db.CookiePlatformRuntimeData
|
||||
// lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。
|
||||
lookupFailed := false
|
||||
// accepted、renewed、renewErr 保存协调器登记结果、续期结果和底层错误。
|
||||
accepted, renewed, renewErr := a.passwordCoordinator.Run(ctx, cookieID, func(runCtx context.Context) (bool, error) {
|
||||
// loaded、loadErr 保存账号平台运行数据及其读取错误。
|
||||
loaded, loadErr := a.store.Cookies.GetCookiePlatformRuntimeData(runCtx, cookieID)
|
||||
if loadErr != nil {
|
||||
lookupFailed = true
|
||||
return false, loadErr
|
||||
}
|
||||
platformData = loaded
|
||||
return a.tryProtocolCredentialRenew(runCtx, &platformData)
|
||||
})
|
||||
sharedRenewed = renewed
|
||||
if !accepted {
|
||||
if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
a.logger.Warn("协议续期协调器不可用", "account", cookieID, "err", renewErr)
|
||||
return false
|
||||
}
|
||||
if lookupFailed {
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", renewErr)
|
||||
// message 保存账号详情读取失败时写入登录审计的脱敏说明。
|
||||
message := "读取账号详情失败"
|
||||
if renewErr != nil {
|
||||
message = renewErr.Error()
|
||||
}
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", message)
|
||||
return false
|
||||
}
|
||||
if renewed {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
|
||||
if renewErr != nil {
|
||||
message += ":" + renewErr.Error()
|
||||
}
|
||||
a.logger.Warn("协议续期未恢复账号", "account", cookieID, "err", renewErr)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountOffline, engine.AlertLevelWarn, "账号需要重新扫码", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "failed", "qr_login_required", message)
|
||||
return false
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 供自动化外部动作在平台明确拒绝旧 Session 后恢复凭证。
|
||||
func (a *Adapter) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
|
||||
return a.OnPasswordLoginRefresh(ctx, cookieID)
|
||||
}
|
||||
|
||||
// OnCredentialUpdated 接收账号运行时保存的新凭证并唤醒失败任务。
|
||||
func (a *Adapter) OnCredentialUpdated(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// OnTransportReady 在 WS 注册完成后立即唤醒发送前明确未执行的任务。
|
||||
func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// beginPasswordLogin 兼容旧测试对账号恢复登记的访问;生产路径统一使用 account.CredentialRefreshCoordinator.Run。
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
if a.passwordCoordinator == nil {
|
||||
return false
|
||||
}
|
||||
return a.passwordCoordinator.TryBegin(cookieID)
|
||||
}
|
||||
|
||||
// finishPasswordLogin 兼容旧测试对账号恢复收尾的访问;正式调用必须由协调器 Run 自动释放状态。
|
||||
func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
if a.passwordCoordinator != nil {
|
||||
a.passwordCoordinator.Finish(cookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// beginPasswordRenewalResult 为账号首次协议续期创建共享结果状态;返回 false 表示已有调用负责续期。
|
||||
func (a *Adapter) beginPasswordRenewalResult(cookieID string) bool {
|
||||
// passwordResultMu 只保护账号到共享结果状态的映射,绝不跨越慢速外部 I/O。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
if a.passwordResults == nil {
|
||||
a.passwordResults = make(map[string]*passwordRenewalResult)
|
||||
}
|
||||
// exists 表示该账号是否已有首个调用负责协议续期,存在时当前调用改为等待共享结果。
|
||||
if _, exists := a.passwordResults[cookieID]; exists {
|
||||
return false
|
||||
}
|
||||
a.passwordResults[cookieID] = &passwordRenewalResult{done: make(chan struct{})}
|
||||
return true
|
||||
}
|
||||
|
||||
// finishPasswordRenewalResult 写入首次协议续期结果并唤醒同账号等待者;重复收尾保持幂等。
|
||||
func (a *Adapter) finishPasswordRenewalResult(cookieID string, renewed bool) {
|
||||
// passwordResultMu 只保护结果写入、映射删除和 channel 关闭的唯一性。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
// result 保存当前账号等待者共享的续期结果状态,负责承载最终结果并关闭通知通道。
|
||||
result := a.passwordResults[cookieID]
|
||||
if result == nil {
|
||||
return
|
||||
}
|
||||
result.renewed = renewed
|
||||
delete(a.passwordResults, cookieID)
|
||||
close(result.done)
|
||||
}
|
||||
|
||||
// waitPasswordRenewalResult 等待首次协议续期完成或调用上下文取消,返回其最终恢复结果。
|
||||
func (a *Adapter) waitPasswordRenewalResult(ctx context.Context, cookieID string) bool {
|
||||
// passwordResultMu 只保护共享状态快照读取,等待发生在释放锁之后。
|
||||
a.passwordResultMu.Lock()
|
||||
// result 保存锁内取得的共享续期状态快照;释放锁后只等待其完成信号。
|
||||
result := a.passwordResults[cookieID]
|
||||
a.passwordResultMu.Unlock()
|
||||
if result == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-result.done:
|
||||
return result.renewed
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// recordPasswordLogin 封装record密码登录业务协调。
|
||||
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
|
||||
if a.store == nil || a.store.LoginLogs == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
CookieID: cookieID,
|
||||
UserID: userID,
|
||||
Method: "protocol",
|
||||
Status: status,
|
||||
Message: truncateMessage(message, 500),
|
||||
TriggerReason: "令牌/Session过期",
|
||||
FailureReason: failureReason,
|
||||
ErrorMessage: truncateMessage(message, 500),
|
||||
AccountIdentifier: cookieID,
|
||||
DurationMS: 0,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}); err != nil {
|
||||
a.logger.Warn("记录协议续期日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateMessage 封装truncate消息业务协调。
|
||||
func truncateMessage(s string, n int) string {
|
||||
if n <= 0 || len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
// tryProtocolCredentialRenew 封装tryProtocolCredentialRenew业务协调。
|
||||
func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePlatformRuntimeData) (bool, error) {
|
||||
if d == nil {
|
||||
return false, nil
|
||||
}
|
||||
// current 用于本次流程后续判断的current
|
||||
current := d.Value
|
||||
// api 用于本次流程后续判断的api
|
||||
api := a.renewSvc
|
||||
// save 用于本次流程后续判断的save
|
||||
save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
|
||||
if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
|
||||
return nil
|
||||
}
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
|
||||
if completeSnapshot != nil {
|
||||
// API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// 服务端删除和新的 Domain/Path/expiry 属性。
|
||||
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
|
||||
return err
|
||||
}
|
||||
// valueChanged 用于本次流程后续判断的值Changed
|
||||
valueChanged := cookieStr != current
|
||||
current = cookieStr
|
||||
d.Value = cookieStr
|
||||
d.MetadataJSON = metadata
|
||||
if valueChanged && a.store.Tokens != nil {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
|
||||
// Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
|
||||
// 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
|
||||
a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
// runCtx、cancel 用于本次流程后续判断的运行Ctx、cancel
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := api.RenewAfterSessionExpired(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
// completeSnapshot 用于本次流程后续判断的completeSnapshot
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
completeSnapshot = res.CookieSnapshot
|
||||
if completeSnapshot == nil {
|
||||
completeSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if // saveErr 用于本次流程后续判断的saveErr
|
||||
saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
// 恢复路径不能把“底层请求仍在进行”提前记为成功,否则上层会
|
||||
// 重置失败计数并继续使用未确认的旧凭证。这里等待最终响应;定时
|
||||
// 调度仍使用异步 watcher,不阻塞健康账号。
|
||||
// waitCtx、waitCancel 用于本次流程后续判断的waitCtx、wait取消
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
// late、waitErr 用于本次流程后续判断的late、waitErr
|
||||
late, waitErr := res.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
return false, errors.New("协议续期底层响应未返回结果")
|
||||
}
|
||||
// lateSnapshot 用于本次流程后续判断的lateSnapshot
|
||||
var lateSnapshot []cookierefresh.BrowserCookie
|
||||
if late.CookieSnapshotComplete {
|
||||
lateSnapshot = late.CookieSnapshot
|
||||
if lateSnapshot == nil {
|
||||
lateSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if // saveErr 用于本次流程后续判断的saveErr
|
||||
saveErr := save(late.NewCookies, late.SetCookies, lateSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
if late.Success {
|
||||
a.logger.Info("Go 协议续期迟到响应成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := strings.TrimSpace(late.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
if err == nil {
|
||||
// message 保存平台续期失败原因;空原因使用稳定的非敏感默认提示。
|
||||
message := strings.TrimSpace(res.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("协议续期未返回结果")
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
var (
|
||||
_ engine.Handler = (*Adapter)(nil)
|
||||
_ automation.OrderDetailFetcher = (*Adapter)(nil)
|
||||
)
|
||||
@@ -0,0 +1,784 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// HandleChatMessage 将已解码的入站聊天消息转交给自动化与通知协作链,返回任一业务处理错误。
|
||||
func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// Xianyu echoes messages sent by this account back over the same WS. Those
|
||||
// sends are already captured by HandleOutgoingChatMessage; recording the
|
||||
// echo as incoming would put our own bubble on the buyer side and duplicate it.
|
||||
// selfID 保存当前账号从 Cookie 解析出的平台用户标识,用于过滤同账号 WebSocket 回显。
|
||||
if selfID := protocol.TransCookies(message.CookieStr)["unb"]; selfID != "" &&
|
||||
strings.TrimSuffix(strings.TrimSpace(message.SenderUserID), "@goofish") == strings.TrimSuffix(strings.TrimSpace(selfID), "@goofish") {
|
||||
a.logger.Info("忽略账号自身发送的聊天回显", "account", message.AccountID, "chat_id", message.ChatID, "sender_id", message.SenderUserID)
|
||||
return nil
|
||||
}
|
||||
// stored、inserted、err 保存落库消息、是否首次插入及持久化错误。
|
||||
stored, inserted, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
|
||||
BuyerName: message.SenderName, Text: message.Text, MessageID: message.MessageID, ItemID: message.ItemID, Raw: message.Raw,
|
||||
})
|
||||
if stored != nil {
|
||||
a.logger.Info("实时聊天消息已入库", "account", message.AccountID, "chat_id", message.ChatID,
|
||||
"message_key", stored.MessageKey, "message_type", stored.MessageType, "inserted", inserted)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleOutgoingChatMessage records successful manual/automatic text sends as
|
||||
// a side channel; it never participates in platform delivery.
|
||||
// HandleOutgoingChatMessage 处理Outgoing聊天消息。
|
||||
func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.OutgoingChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.chat.RecordOutgoingSent(ctx, db.ChatSession{CookieID: message.AccountID, ChatID: message.ChatID,
|
||||
BuyerID: message.BuyerID}, message.MessageKey, message.Text)
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleMessageRead 接收平台出站消息已读回执,并把非敏感已读状态更新委托给聊天服务。
|
||||
func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// message、err 保存按平台消息键更新的出站消息及持久化错误,以便缺键时回退会话最近消息。
|
||||
message, err := a.chat.MarkOutgoingRead(ctx, event.AccountID, event.MessageID, event.ReadAt)
|
||||
if errors.Is(err, db.ErrNotFound) && event.ChatID != "" {
|
||||
message, err = a.chat.MarkLatestOutgoingRead(ctx, event.AccountID, event.ChatID, event.ReadAt)
|
||||
}
|
||||
if err == nil && message != nil {
|
||||
a.logger.Info("聊天出站消息已标记已读", "account", event.AccountID, "chat_id", event.ChatID,
|
||||
"message_id", event.MessageID, "message_key", message.MessageKey, "read_status", message.ReadStatus)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
// OnAccountAlert 封装On账号Alert业务协调。
|
||||
func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) {
|
||||
a.OnAccountEvent(ctx, cookieID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
|
||||
// OnAccountEvent 把带类型的账号事件转发给通知器。
|
||||
func (a *Adapter) OnAccountEvent(_ context.Context, cookieID, eventType, level, title, body string) {
|
||||
if a.notifier == nil {
|
||||
a.logger.Warn("账号事件通知未发送:通知器未注入", "account", cookieID, "event_type", eventType, "level", level, "title", title)
|
||||
return
|
||||
}
|
||||
if // n、ok 用于本次流程后续判断的n、ok
|
||||
n, ok := a.notifier.(notifyEventNotifier); ok {
|
||||
n.NotifyAccountEvent(cookieID, eventType, level, title, body)
|
||||
return
|
||||
}
|
||||
a.notifier.NotifyAccountAlert(cookieID, level, title, body)
|
||||
}
|
||||
|
||||
// classifyAccountAlertEvent 封装classify账号AlertEvent业务协调。
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
strings.Contains(msg, "滑块"), strings.Contains(msg, "captcha"),
|
||||
strings.Contains(msg, "risk"), strings.Contains(msg, "x5sec"):
|
||||
return engine.EventSecurityVerification
|
||||
case strings.Contains(msg, "禁用"), strings.Contains(msg, "disabled"):
|
||||
return engine.EventAccountDisabled
|
||||
case strings.Contains(msg, "掉线"), strings.Contains(msg, "离线"),
|
||||
strings.Contains(msg, "offline"), strings.Contains(msg, "session"),
|
||||
strings.Contains(msg, "登录凭证已失效"):
|
||||
return engine.EventAccountOffline
|
||||
case strings.Contains(msg, "token"), strings.Contains(msg, "续期"), strings.Contains(msg, "renew"):
|
||||
return engine.EventTokenRenewal
|
||||
default:
|
||||
return engine.EventSystemError
|
||||
}
|
||||
}
|
||||
|
||||
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL, deviceID string) (*mtop.RefreshResult, bool) {
|
||||
// start 用于本次流程后续判断的开始
|
||||
start := time.Now()
|
||||
// logID 用于本次流程后续判断的logID
|
||||
var logID int64
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
if // id、err 用于本次流程后续判断的id、err
|
||||
id, err := a.store.RiskLogs.Add(ctx, db.RiskControlLog{
|
||||
CookieID: cookieID,
|
||||
EventType: "slider_captcha",
|
||||
EventDescription: "触发场景: Token刷新, URL: " + verificationURL,
|
||||
ProcessingStatus: "processing",
|
||||
}); err == nil {
|
||||
logID = id
|
||||
} else {
|
||||
a.logger.Warn("记录风控日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// showBrowser 用于本次流程后续判断的show浏览器
|
||||
showBrowser := false
|
||||
// metadataJSON 用于本次流程后续判断的metadataJSON
|
||||
metadataJSON := ""
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法保存", "账号存储未初始化,无法保存验证后的 Cookie。")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if // d、err 用于本次流程后续判断的d、err
|
||||
d, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID); err == nil {
|
||||
showBrowser = d.ShowBrowser
|
||||
metadataJSON = d.MetadataJSON
|
||||
}
|
||||
|
||||
// provider 用于本次流程后续判断的provider
|
||||
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
|
||||
if a.captchaReq == nil {
|
||||
return "", false, "", nil
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.captchaReq.RequestFreshCaptchaURLContext(runCtx, currentCookies, deviceID)
|
||||
if err != nil || res == nil {
|
||||
return "", false, "", err
|
||||
}
|
||||
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
// newCookies 用于本次流程后续判断的newCookies
|
||||
newCookies := ""
|
||||
// captchaEngine 用于本次流程后续判断的captchaEngine
|
||||
captchaEngine := "playwright"
|
||||
// remoteHandled 用于本次流程后续判断的remoteHandled
|
||||
remoteHandled := false
|
||||
// captchaHeadless 用于本次流程后续判断的captchaHeadless
|
||||
captchaHeadless := browser.ResolveHeadless(showBrowser)
|
||||
// err 用于本次流程后续判断的err
|
||||
var err error
|
||||
if // remoteConfig 用于本次流程后续判断的remote配置
|
||||
remoteConfig := a.loadRemoteCaptchaConfig(ctx, cookieID); remoteConfig != nil {
|
||||
newCookies, remoteHandled, err = solveRemoteCaptcha(
|
||||
ctx, newRemoteCaptchaHTTPClient(), *remoteConfig,
|
||||
cookieID, verificationURL, cookieStr, deviceID, provider,
|
||||
)
|
||||
if remoteHandled {
|
||||
captchaEngine = "remote"
|
||||
} else if err != nil {
|
||||
a.logger.Warn("远程过滑块不可用,回退本机逻辑", "account", cookieID, "err", err)
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
if !remoteHandled {
|
||||
// br、ok 用于本次流程后续判断的br、ok
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "远程服务不可用且浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return nil, false
|
||||
}
|
||||
if // withEngine、ok 用于本次流程后续判断的withEngine、ok
|
||||
withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
} else {
|
||||
newCookies, err = br.TokenCaptchaRecover(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
// manualURL 用于本次流程后续判断的manualURL
|
||||
manualURL := browser.TokenCaptchaManualVerificationURL(err)
|
||||
if strings.TrimSpace(manualURL) == "" {
|
||||
manualURL = verificationURL
|
||||
}
|
||||
a.logger.Warn("token 风控滑块处理失败", "account", cookieID, "err", logsafe.Error(err), "verification_url", logsafe.URL(manualURL))
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "failed",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块处理失败,耗时: %.2f秒", time.Since(start).Seconds()),
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证失败", err.Error())
|
||||
return nil, false
|
||||
}
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
// cookieSnapshot 用于本次流程后续判断的登录凭证Snapshot
|
||||
var cookieSnapshot []cookierefresh.BrowserCookie
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
snapshotComplete := false
|
||||
if !remoteHandled {
|
||||
if // reader、ok 用于本次流程后续判断的reader、ok
|
||||
reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
// profileCookies、profileSnapshot、readErr 用于本次流程后续判断的profileCookies、profileSnapshot、readErr
|
||||
profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
|
||||
if readErr != nil {
|
||||
a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
|
||||
} else {
|
||||
cookieSnapshot = cookierefresh.NormalizeSnapshot(profileSnapshot)
|
||||
if cookieSnapshot == nil {
|
||||
cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
snapshotComplete = true
|
||||
newCookies = profileCookies
|
||||
}
|
||||
}
|
||||
}
|
||||
if !snapshotComplete {
|
||||
if // existing、complete 用于本次流程后续判断的existing、complete
|
||||
existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
|
||||
snapshotComplete = true
|
||||
}
|
||||
}
|
||||
// updatedMetadata 用于本次流程后续判断的updatedMetadata
|
||||
updatedMetadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshotComplete {
|
||||
updatedMetadata = cookierefresh.MetadataWithSnapshot(metadataJSON, cookieSnapshot)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, updatedMetadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "error",
|
||||
ProcessingResult: "滑块完成但保存 Cookie 失败",
|
||||
CaptchaEngine: captchaEngine,
|
||||
ErrorMessage: err.Error(),
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
ProcessingStatus: "success",
|
||||
ProcessingResult: fmt.Sprintf("token 风控滑块验证成功(%s),已更新登录凭证,耗时: %.2f秒", captchaEngine, time.Since(start).Seconds()),
|
||||
CaptchaEngine: captchaEngine,
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
})
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
|
||||
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
|
||||
return &mtop.RefreshResult{
|
||||
UpdatedCookies: newCookies,
|
||||
CookieSnapshot: cookieSnapshot,
|
||||
CookieSnapshotComplete: snapshotComplete,
|
||||
CookieStateChanged: newCookies != cookieStr || snapshotComplete,
|
||||
}, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) error {
|
||||
if a.automation == nil {
|
||||
return nil
|
||||
}
|
||||
a.logger.Info("系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
|
||||
// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
// FetchOrderDetail 封装Fetch订单Detail业务协调。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
|
||||
if // detail、ok 用于本次流程后续判断的detail、ok
|
||||
detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
// detail、err 用于本次流程后续判断的detail、err
|
||||
detail, err := a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
if err == nil || !mtop.IsSessionExpiredErr(err) {
|
||||
return detail, err
|
||||
}
|
||||
a.logger.Warn("订单详情检测到 Session 过期,开始即时续期", "account", cookieID, "order_id", orderID)
|
||||
if !a.OnPasswordLoginRefresh(ctx, cookieID) {
|
||||
return nil, fmt.Errorf("订单详情 Session 过期且即时续期失败: %w", err)
|
||||
}
|
||||
a.logger.Info("Cookie 即时续期成功,重新请求订单详情", "account", cookieID, "order_id", orderID)
|
||||
return a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
}
|
||||
|
||||
// fetchOrderDetailAttempt 封装fetch订单Detail尝试次数业务协调。
|
||||
func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID string) (*automation.OrderDetail, error) {
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
defer a.orderFetchMu.Unlock()
|
||||
// 等锁期间其他流程可能已经补齐订单,再检查一次。
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if // remain 用于本次流程后续判断的remain
|
||||
remain := 3*time.Second - time.Since(a.lastOrderFetch); !a.lastOrderFetch.IsZero() && remain > 0 {
|
||||
// timer 用于本次流程后续判断的定时器
|
||||
timer := time.NewTimer(remain)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
a.lastOrderFetch = time.Now()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := a.store.LockAccountCredentials(cookieID)
|
||||
// credentialLocked 标识当前调用是否持有账号凭证锁。
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 只包含订单 MTOP 请求所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(platformData.Value) == "" && !hasCompleteCookieSnapshot(platformData.MetadataJSON) {
|
||||
return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
|
||||
}
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := platformData.Value
|
||||
// requestCtx 用于本次流程后续判断的请求Ctx
|
||||
var requestCtx context.Context
|
||||
// cookieSession 用于本次流程后续判断的登录凭证会话
|
||||
var cookieSession *mtop.CookieSession
|
||||
if // snapshot、complete 用于本次流程后续判断的snapshot、complete
|
||||
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(platformData.MetadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
// 账号凭证快照已读取完成;慢速 MTOP 请求不得继续持有共享凭证锁。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
// detail、fetchErr 用于本次流程后续判断的detail、fetchErr
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
// authoritativeCookies、authoritativeSnapshot、sessionChanged 用于本次流程后续判断的authoritativeCookies、authoritativeSnapshot、sessionChanged
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
// credentialUnlock 保存重新进入凭证提交临界区的释放函数。
|
||||
credentialUnlock = a.store.LockAccountCredentials(cookieID)
|
||||
credentialLocked = true
|
||||
// latestPlatformData 和 reloadErr 保存外部调用完成后的最新凭证快照及重读错误。
|
||||
latestPlatformData, reloadErr := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
|
||||
if reloadErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("重读订单账号最新 Cookie: %w", reloadErr))
|
||||
} else if latestPlatformData.Value != platformData.Value || latestPlatformData.MetadataJSON != platformData.MetadataJSON {
|
||||
// 凭证在外部调用期间已被其他流程更新,丢弃旧快照响应,避免覆盖更新后的状态。
|
||||
sessionChanged = false
|
||||
authoritativeSnapshot = nil
|
||||
} else if sessionChanged {
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(latestPlatformData.MetadataJSON, authoritativeSnapshot)
|
||||
}
|
||||
if // persistErr 用于本次流程后续判断的persistErr
|
||||
persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
}
|
||||
if fetchErr != nil {
|
||||
return nil, fetchErr
|
||||
}
|
||||
if detail == nil {
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if reloadErr == nil && latestPlatformData.Value == platformData.Value && latestPlatformData.MetadataJSON == platformData.MetadataJSON && !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
// 外部调用产生的凭证结果已处理完成,释放短暂提交临界区。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
Amount: detail.Amount, OrderStatus: detail.OrderStatus,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// wakeCredentialBlockedAutomation 封装wakeCredentialBlocked自动化业务协调。
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.credentialWake == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.credentialWake.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// hasCompleteCookieSnapshot 封装hasComplete登录凭证Snapshot业务协调。
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
// ok 用于本次流程后续判断的ok
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
|
||||
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
|
||||
// order、err 用于本次流程后续判断的order、err
|
||||
order, err := a.store.Orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
return nil, false
|
||||
}
|
||||
if order.Amount == "" || order.Quantity == "" || order.SpecName == "" || order.SpecValue == "" {
|
||||
return nil, false
|
||||
}
|
||||
return &automation.OrderDetail{
|
||||
Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue,
|
||||
Amount: order.Amount, OrderStatus: order.OrderStatus,
|
||||
}, true
|
||||
}
|
||||
|
||||
// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
|
||||
// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
|
||||
// OnPasswordLoginRefresh 封装On密码登录Refresh业务协调。
|
||||
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
|
||||
// cooldown 用于本次流程后续判断的cooldown
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if // ok、remain、reason 用于本次流程后续判断的ok、remain、reason
|
||||
ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
|
||||
a.logger.Warn("协议续期冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
// primary 标识当前调用是否负责执行协议续期;后到调用方只等待其结果。
|
||||
if primary := a.beginPasswordRenewalResult(cookieID); !primary {
|
||||
a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID)
|
||||
return a.waitPasswordRenewalResult(ctx, cookieID)
|
||||
}
|
||||
// sharedRenewed 保存首次调用的最终恢复结果,并在所有返回路径唤醒等待者。
|
||||
sharedRenewed := false
|
||||
defer func() { a.finishPasswordRenewalResult(cookieID, sharedRenewed) }()
|
||||
// platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。
|
||||
var platformData db.CookiePlatformRuntimeData
|
||||
// lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。
|
||||
lookupFailed := false
|
||||
// accepted、renewed、renewErr 保存协调器登记结果、续期结果和底层错误。
|
||||
accepted, renewed, renewErr := a.passwordCoordinator.Run(ctx, cookieID, func(runCtx context.Context) (bool, error) {
|
||||
// loaded、loadErr 保存账号平台运行数据及其读取错误。
|
||||
loaded, loadErr := a.store.Cookies.GetCookiePlatformRuntimeData(runCtx, cookieID)
|
||||
if loadErr != nil {
|
||||
lookupFailed = true
|
||||
return false, loadErr
|
||||
}
|
||||
platformData = loaded
|
||||
return a.tryProtocolCredentialRenew(runCtx, &platformData)
|
||||
})
|
||||
sharedRenewed = renewed
|
||||
if !accepted {
|
||||
if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
a.logger.Warn("协议续期协调器不可用", "account", cookieID, "err", renewErr)
|
||||
return false
|
||||
}
|
||||
if lookupFailed {
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", renewErr)
|
||||
// message 保存账号详情读取失败时写入登录审计的脱敏说明。
|
||||
message := "读取账号详情失败"
|
||||
if renewErr != nil {
|
||||
message = renewErr.Error()
|
||||
}
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", message)
|
||||
return false
|
||||
}
|
||||
if renewed {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
|
||||
if renewErr != nil {
|
||||
message += ":" + renewErr.Error()
|
||||
}
|
||||
a.logger.Warn("协议续期未恢复账号", "account", cookieID, "err", renewErr)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountOffline, engine.AlertLevelWarn, "账号需要重新扫码", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "failed", "qr_login_required", message)
|
||||
return false
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 供自动化外部动作在平台明确拒绝旧 Session 后恢复凭证。
|
||||
func (a *Adapter) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
|
||||
return a.OnPasswordLoginRefresh(ctx, cookieID)
|
||||
}
|
||||
|
||||
// OnCredentialUpdated 接收账号运行时保存的新凭证并唤醒失败任务。
|
||||
func (a *Adapter) OnCredentialUpdated(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// OnTransportReady 在 WS 注册完成后立即唤醒发送前明确未执行的任务。
|
||||
func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// beginPasswordLogin 兼容旧测试对账号恢复登记的访问;生产路径统一使用 account.CredentialRefreshCoordinator.Run。
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
if a.passwordCoordinator == nil {
|
||||
return false
|
||||
}
|
||||
return a.passwordCoordinator.TryBegin(cookieID)
|
||||
}
|
||||
|
||||
// finishPasswordLogin 兼容旧测试对账号恢复收尾的访问;正式调用必须由协调器 Run 自动释放状态。
|
||||
func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
if a.passwordCoordinator != nil {
|
||||
a.passwordCoordinator.Finish(cookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// beginPasswordRenewalResult 为账号首次协议续期创建共享结果状态;返回 false 表示已有调用负责续期。
|
||||
func (a *Adapter) beginPasswordRenewalResult(cookieID string) bool {
|
||||
// passwordResultMu 只保护账号到共享结果状态的映射,绝不跨越慢速外部 I/O。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
if a.passwordResults == nil {
|
||||
a.passwordResults = make(map[string]*passwordRenewalResult)
|
||||
}
|
||||
// exists 表示该账号是否已有首个调用负责协议续期,存在时当前调用改为等待共享结果。
|
||||
if _, exists := a.passwordResults[cookieID]; exists {
|
||||
return false
|
||||
}
|
||||
a.passwordResults[cookieID] = &passwordRenewalResult{done: make(chan struct{})}
|
||||
return true
|
||||
}
|
||||
|
||||
// finishPasswordRenewalResult 写入首次协议续期结果并唤醒同账号等待者;重复收尾保持幂等。
|
||||
func (a *Adapter) finishPasswordRenewalResult(cookieID string, renewed bool) {
|
||||
// passwordResultMu 只保护结果写入、映射删除和 channel 关闭的唯一性。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
// result 保存当前账号等待者共享的续期结果状态,负责承载最终结果并关闭通知通道。
|
||||
result := a.passwordResults[cookieID]
|
||||
if result == nil {
|
||||
return
|
||||
}
|
||||
result.renewed = renewed
|
||||
delete(a.passwordResults, cookieID)
|
||||
close(result.done)
|
||||
}
|
||||
|
||||
// waitPasswordRenewalResult 等待首次协议续期完成或调用上下文取消,返回其最终恢复结果。
|
||||
func (a *Adapter) waitPasswordRenewalResult(ctx context.Context, cookieID string) bool {
|
||||
// passwordResultMu 只保护共享状态快照读取,等待发生在释放锁之后。
|
||||
a.passwordResultMu.Lock()
|
||||
// result 保存锁内取得的共享续期状态快照;释放锁后只等待其完成信号。
|
||||
result := a.passwordResults[cookieID]
|
||||
a.passwordResultMu.Unlock()
|
||||
if result == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-result.done:
|
||||
return result.renewed
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// recordPasswordLogin 封装record密码登录业务协调。
|
||||
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
|
||||
if a.store == nil || a.store.LoginLogs == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
CookieID: cookieID,
|
||||
UserID: userID,
|
||||
Method: "protocol",
|
||||
Status: status,
|
||||
Message: truncateMessage(message, 500),
|
||||
TriggerReason: "令牌/Session过期",
|
||||
FailureReason: failureReason,
|
||||
ErrorMessage: truncateMessage(message, 500),
|
||||
AccountIdentifier: cookieID,
|
||||
DurationMS: 0,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}); err != nil {
|
||||
a.logger.Warn("记录协议续期日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateMessage 封装truncate消息业务协调。
|
||||
func truncateMessage(s string, n int) string {
|
||||
if n <= 0 || len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
// tryProtocolCredentialRenew 封装tryProtocolCredentialRenew业务协调。
|
||||
func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePlatformRuntimeData) (bool, error) {
|
||||
if d == nil {
|
||||
return false, nil
|
||||
}
|
||||
// current 用于本次流程后续判断的current
|
||||
current := d.Value
|
||||
// api 用于本次流程后续判断的api
|
||||
api := a.renewSvc
|
||||
// save 用于本次流程后续判断的save
|
||||
save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
|
||||
if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
|
||||
return nil
|
||||
}
|
||||
// metadata 用于本次流程后续判断的metadata
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
|
||||
if completeSnapshot != nil {
|
||||
// API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// 服务端删除和新的 Domain/Path/expiry 属性。
|
||||
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
|
||||
return err
|
||||
}
|
||||
// valueChanged 用于本次流程后续判断的值Changed
|
||||
valueChanged := cookieStr != current
|
||||
current = cookieStr
|
||||
d.Value = cookieStr
|
||||
d.MetadataJSON = metadata
|
||||
if valueChanged && a.store.Tokens != nil {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
|
||||
// Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
|
||||
// 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
|
||||
a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
// runCtx、cancel 用于本次流程后续判断的运行Ctx、cancel
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := api.RenewAfterSessionExpired(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
// completeSnapshot 用于本次流程后续判断的completeSnapshot
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
completeSnapshot = res.CookieSnapshot
|
||||
if completeSnapshot == nil {
|
||||
completeSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if // saveErr 用于本次流程后续判断的saveErr
|
||||
saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
// 恢复路径不能把“底层请求仍在进行”提前记为成功,否则上层会
|
||||
// 重置失败计数并继续使用未确认的旧凭证。这里等待最终响应;定时
|
||||
// 调度仍使用异步 watcher,不阻塞健康账号。
|
||||
// waitCtx、waitCancel 用于本次流程后续判断的waitCtx、wait取消
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
// late、waitErr 用于本次流程后续判断的late、waitErr
|
||||
late, waitErr := res.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
return false, errors.New("协议续期底层响应未返回结果")
|
||||
}
|
||||
// lateSnapshot 用于本次流程后续判断的lateSnapshot
|
||||
var lateSnapshot []cookierefresh.BrowserCookie
|
||||
if late.CookieSnapshotComplete {
|
||||
lateSnapshot = late.CookieSnapshot
|
||||
if lateSnapshot == nil {
|
||||
lateSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if // saveErr 用于本次流程后续判断的saveErr
|
||||
saveErr := save(late.NewCookies, late.SetCookies, lateSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
if late.Success {
|
||||
a.logger.Info("Go 协议续期迟到响应成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := strings.TrimSpace(late.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
if err == nil {
|
||||
// message 保存平台续期失败原因;空原因使用稳定的非敏感默认提示。
|
||||
message := strings.TrimSpace(res.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("协议续期未返回结果")
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
var (
|
||||
_ engine.Handler = (*Adapter)(nil)
|
||||
_ automation.OrderDetailFetcher = (*Adapter)(nil)
|
||||
)
|
||||
@@ -585,132 +585,6 @@ func xmlCharData(inner string) string {
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
// normalizeHeaders 将用户表头映射为稳定的应用字段名。
|
||||
func normalizeHeaders(headers []string) []string {
|
||||
// keys 保存归一化后的字段名。
|
||||
keys := make([]string, len(headers))
|
||||
// index 和 header 表示表头下标及原始文本。
|
||||
for index, header := range headers {
|
||||
keys[index] = normalizeHeader(header)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// rowMap 将一行单元格按表头映射为字符串字段。
|
||||
func rowMap(keys, values []string) (map[string]any, bool) {
|
||||
// result 保存表头到单元格值的映射。
|
||||
result := map[string]any{}
|
||||
// nonEmpty 表示当前行是否包含有效文本。
|
||||
nonEmpty := false
|
||||
// index 和 key 表示当前列下标及归一化字段名。
|
||||
for index, key := range keys {
|
||||
if key == "" || index >= len(values) {
|
||||
continue
|
||||
}
|
||||
// value 保存当前单元格的裁剪后文本。
|
||||
value := strings.TrimSpace(values[index])
|
||||
if value != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
return result, nonEmpty
|
||||
}
|
||||
|
||||
// normalizeHeader 将中英文表头归一化为应用字段名。
|
||||
func normalizeHeader(header string) string {
|
||||
// value 保存去除空白和分隔符后的表头文本。
|
||||
value := strings.ToLower(strings.TrimSpace(header))
|
||||
value = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(value)
|
||||
switch value {
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "title", "itemtitle", "标题", "商品标题", "商品名称":
|
||||
return "title"
|
||||
case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情":
|
||||
return "description"
|
||||
case "price", "itemprice", "价格", "商品价格":
|
||||
return "price"
|
||||
case "originalprice", "原价":
|
||||
return "original_price"
|
||||
case "quantity", "库存", "数量":
|
||||
return "quantity"
|
||||
case "postagemode", "邮费模式":
|
||||
return "postage_mode"
|
||||
case "postage", "邮费":
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "categoryid", "catid", "类目id", "商品类目id":
|
||||
return "category_id"
|
||||
case "categoryname", "catname", "类目名称", "商品类目名称", "类目":
|
||||
return "category_name"
|
||||
case "channelcategoryid", "channelcatid", "频道类目id":
|
||||
return "channel_category_id"
|
||||
case "tbcategoryid", "tbcatid", "淘宝类目id":
|
||||
return "tb_category_id"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
return "paid_delivery_contents"
|
||||
case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品":
|
||||
return "review_gift_enabled"
|
||||
case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密":
|
||||
return "review_gift_contents"
|
||||
case "reviewrequestenabled", "求评价启用", "超时未评价时提醒":
|
||||
return "review_request_enabled"
|
||||
case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒":
|
||||
return "review_request_after_hours"
|
||||
case "reviewrequestmessage", "求评价文案", "提醒内容":
|
||||
return "review_request_message"
|
||||
case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次":
|
||||
return "review_request_max_attempts"
|
||||
case "reviewrequestdelayseconds", "求评价延迟秒":
|
||||
return "review_request_delay_seconds"
|
||||
default:
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
}
|
||||
|
||||
// firstString 从字段映射中返回首个非空字符串。
|
||||
func firstString(fields map[string]any, keys ...string) string {
|
||||
// key 表示当前候选字段名。
|
||||
for _, key := range keys {
|
||||
// value 和 ok 表示字段原始值及是否存在。
|
||||
if value, ok := fields[key]; ok {
|
||||
// text 保存字段的字符串表示。
|
||||
text := stringValue(value)
|
||||
if strings.TrimSpace(text) != "" {
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// stringValue 将常见表格值转换为文本。
|
||||
func stringValue(value any) string {
|
||||
// typed 保存类型断言后的常见表格值。
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return typed
|
||||
case float64:
|
||||
return strconv.FormatFloat(typed, 'f', -1, 64)
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(typed), 'f', -1, 32)
|
||||
case int:
|
||||
return strconv.Itoa(typed)
|
||||
case int64:
|
||||
return strconv.FormatInt(typed, 10)
|
||||
case bool:
|
||||
return strconv.FormatBool(typed)
|
||||
default:
|
||||
return fmt.Sprint(typed)
|
||||
}
|
||||
}
|
||||
|
||||
// parseIntDefault 将数字文本转换为整数,失败时返回默认值。
|
||||
func parseIntDefault(raw string, fallback int) int {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// normalizeHeaders 将用户表头映射为稳定的应用字段名。
|
||||
func normalizeHeaders(headers []string) []string {
|
||||
// keys 保存归一化后的字段名。
|
||||
keys := make([]string, len(headers))
|
||||
// index 和 header 表示表头下标及原始文本。
|
||||
for index, header := range headers {
|
||||
keys[index] = normalizeHeader(header)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// rowMap 将一行单元格按表头映射为字符串字段。
|
||||
func rowMap(keys, values []string) (map[string]any, bool) {
|
||||
// result 保存表头到单元格值的映射。
|
||||
result := map[string]any{}
|
||||
// nonEmpty 表示当前行是否包含有效文本。
|
||||
nonEmpty := false
|
||||
// index 和 key 表示当前列下标及归一化字段名。
|
||||
for index, key := range keys {
|
||||
if key == "" || index >= len(values) {
|
||||
continue
|
||||
}
|
||||
// value 保存当前单元格的裁剪后文本。
|
||||
value := strings.TrimSpace(values[index])
|
||||
if value != "" {
|
||||
nonEmpty = true
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
return result, nonEmpty
|
||||
}
|
||||
|
||||
// normalizeHeader 将中英文表头归一化为应用字段名。
|
||||
func normalizeHeader(header string) string {
|
||||
// value 保存去除空白和分隔符后的表头文本。
|
||||
value := strings.ToLower(strings.TrimSpace(header))
|
||||
value = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(value)
|
||||
switch value {
|
||||
case "cookieid", "账号id", "账号", "闲鱼账号":
|
||||
return "cookie_id"
|
||||
case "title", "itemtitle", "标题", "商品标题", "商品名称":
|
||||
return "title"
|
||||
case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情":
|
||||
return "description"
|
||||
case "price", "itemprice", "价格", "商品价格":
|
||||
return "price"
|
||||
case "originalprice", "原价":
|
||||
return "original_price"
|
||||
case "quantity", "库存", "数量":
|
||||
return "quantity"
|
||||
case "postagemode", "邮费模式":
|
||||
return "postage_mode"
|
||||
case "postage", "邮费":
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "categoryid", "catid", "类目id", "商品类目id":
|
||||
return "category_id"
|
||||
case "categoryname", "catname", "类目名称", "商品类目名称", "类目":
|
||||
return "category_name"
|
||||
case "channelcategoryid", "channelcatid", "频道类目id":
|
||||
return "channel_category_id"
|
||||
case "tbcategoryid", "tbcatid", "淘宝类目id":
|
||||
return "tb_category_id"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
return "paid_delivery_contents"
|
||||
case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品":
|
||||
return "review_gift_enabled"
|
||||
case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密":
|
||||
return "review_gift_contents"
|
||||
case "reviewrequestenabled", "求评价启用", "超时未评价时提醒":
|
||||
return "review_request_enabled"
|
||||
case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒":
|
||||
return "review_request_after_hours"
|
||||
case "reviewrequestmessage", "求评价文案", "提醒内容":
|
||||
return "review_request_message"
|
||||
case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次":
|
||||
return "review_request_max_attempts"
|
||||
case "reviewrequestdelayseconds", "求评价延迟秒":
|
||||
return "review_request_delay_seconds"
|
||||
default:
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
}
|
||||
|
||||
// firstString 从字段映射中返回首个非空字符串。
|
||||
func firstString(fields map[string]any, keys ...string) string {
|
||||
// key 是当前按优先级读取的候选字段名。
|
||||
for _, key := range keys {
|
||||
// value、ok 分别是字段原始值和其是否存在于当前行。
|
||||
if value, ok := fields[key]; ok {
|
||||
// text 是字段统一转换后的候选非空文本。
|
||||
if text := stringValue(value); strings.TrimSpace(text) != "" {
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// stringValue 将常见表格值转换为文本。
|
||||
func stringValue(value any) string {
|
||||
// typed 是当前字段值断言后的具体基础类型。
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return typed
|
||||
case float64:
|
||||
return strconv.FormatFloat(typed, 'f', -1, 64)
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(typed), 'f', -1, 32)
|
||||
case int:
|
||||
return strconv.Itoa(typed)
|
||||
case int64:
|
||||
return strconv.FormatInt(typed, 10)
|
||||
case bool:
|
||||
return strconv.FormatBool(typed)
|
||||
default:
|
||||
return fmt.Sprint(typed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package orders
|
||||
|
||||
// refreshWrite 保存详情分片中等待事务写入的单条订单。
|
||||
type refreshWrite struct {
|
||||
// OrderID 是待更新订单标识。
|
||||
OrderID string
|
||||
// CurrentStatus 是刷新前订单状态。
|
||||
CurrentStatus string
|
||||
// NewStatus 是刷新后订单状态。
|
||||
NewStatus string
|
||||
// Options 是订单写入字段。
|
||||
Options UpsertOptions
|
||||
// CookieUpdate 是本次详情请求观察到的 Cookie 更新。
|
||||
CookieUpdate RefreshCookieUpdate
|
||||
}
|
||||
|
||||
// refreshTarget 保存待补全详情的订单目标。
|
||||
type refreshTarget struct {
|
||||
// OrderID 是待刷新订单标识。
|
||||
OrderID string
|
||||
// CurrentStatus 是本地当前订单状态。
|
||||
CurrentStatus string
|
||||
}
|
||||
|
||||
// refreshSoldOrderChanged 判断平台订单字段是否发生业务变化。
|
||||
func refreshSoldOrderChanged(existing *Order, remote RefreshSoldOrder) bool {
|
||||
if existing == nil {
|
||||
return true
|
||||
}
|
||||
return (remote.OrderStatus != "" && remote.OrderStatus != "unknown" && NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus) ||
|
||||
(remote.ItemID != "" && existing.ItemID != remote.ItemID) ||
|
||||
(remote.BuyerID != "" && existing.BuyerID != remote.BuyerID) ||
|
||||
(remote.Quantity != "" && existing.Quantity != remote.Quantity) ||
|
||||
(remote.Amount != "" && existing.Amount != remote.Amount) ||
|
||||
(remote.ReceiverName != "" && existing.ReceiverName != remote.ReceiverName) ||
|
||||
(remote.ReceiverPhone != "" && existing.ReceiverPhone != remote.ReceiverPhone) ||
|
||||
(remote.ReceiverAddr != "" && existing.ReceiverAddress != remote.ReceiverAddr) ||
|
||||
(remote.ReceiverCity != "" && existing.ReceiverCity != remote.ReceiverCity) ||
|
||||
(remote.IsBargain && existing.IsBargain == 0)
|
||||
}
|
||||
|
||||
// isStableRefreshStatus 判断订单是否处于无需重复详情抓取的稳定状态。
|
||||
func isStableRefreshStatus(status string) bool {
|
||||
switch status {
|
||||
case "shipped", "completed", "cancelled":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// splitRefreshTargets 按固定大小切分订单刷新目标。
|
||||
func splitRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
|
||||
if size <= 0 {
|
||||
size = 100
|
||||
}
|
||||
// chunks 保存切分后的详情目标分片。
|
||||
chunks := make([][]refreshTarget, 0, (len(targets)+size-1)/size)
|
||||
// start 是当前分片起始下标。
|
||||
for start := 0; start < len(targets); start += size {
|
||||
// end 是当前分片结束下标。
|
||||
end := start + size
|
||||
if end > len(targets) {
|
||||
end = len(targets)
|
||||
}
|
||||
chunks = append(chunks, targets[start:end])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
@@ -731,71 +731,3 @@ func (s *RefreshService) refreshDetailChunk(ctx context.Context, userID int64, c
|
||||
}
|
||||
return updated, noChange, failed, results, sessionErr != nil
|
||||
}
|
||||
|
||||
// refreshWrite 保存详情分片中等待事务写入的单条订单。
|
||||
type refreshWrite struct {
|
||||
// OrderID 是待更新订单标识。
|
||||
OrderID string
|
||||
// CurrentStatus 是刷新前订单状态。
|
||||
CurrentStatus string
|
||||
// NewStatus 是刷新后订单状态。
|
||||
NewStatus string
|
||||
// Options 是订单写入字段。
|
||||
Options UpsertOptions
|
||||
// CookieUpdate 是本次详情请求观察到的 Cookie 更新。
|
||||
CookieUpdate RefreshCookieUpdate
|
||||
}
|
||||
|
||||
// refreshTarget 保存待补全详情的订单目标。
|
||||
type refreshTarget struct {
|
||||
// OrderID 是待刷新订单标识。
|
||||
OrderID string
|
||||
// CurrentStatus 是本地当前订单状态。
|
||||
CurrentStatus string
|
||||
}
|
||||
|
||||
// refreshSoldOrderChanged 判断平台订单字段是否发生业务变化。
|
||||
func refreshSoldOrderChanged(existing *Order, remote RefreshSoldOrder) bool {
|
||||
if existing == nil {
|
||||
return true
|
||||
}
|
||||
return (remote.OrderStatus != "" && remote.OrderStatus != "unknown" && NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus) ||
|
||||
(remote.ItemID != "" && existing.ItemID != remote.ItemID) ||
|
||||
(remote.BuyerID != "" && existing.BuyerID != remote.BuyerID) ||
|
||||
(remote.Quantity != "" && existing.Quantity != remote.Quantity) ||
|
||||
(remote.Amount != "" && existing.Amount != remote.Amount) ||
|
||||
(remote.ReceiverName != "" && existing.ReceiverName != remote.ReceiverName) ||
|
||||
(remote.ReceiverPhone != "" && existing.ReceiverPhone != remote.ReceiverPhone) ||
|
||||
(remote.ReceiverAddr != "" && existing.ReceiverAddress != remote.ReceiverAddr) ||
|
||||
(remote.ReceiverCity != "" && existing.ReceiverCity != remote.ReceiverCity) ||
|
||||
(remote.IsBargain && existing.IsBargain == 0)
|
||||
}
|
||||
|
||||
// isStableRefreshStatus 判断订单是否处于无需重复详情抓取的稳定状态。
|
||||
func isStableRefreshStatus(status string) bool {
|
||||
switch status {
|
||||
case "shipped", "completed", "cancelled":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// splitRefreshTargets 按固定大小切分订单刷新目标。
|
||||
func splitRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
|
||||
if size <= 0 {
|
||||
size = 100
|
||||
}
|
||||
// chunks 保存切分后的详情目标分片。
|
||||
chunks := make([][]refreshTarget, 0, (len(targets)+size-1)/size)
|
||||
// start 是当前分片起始下标。
|
||||
for start := 0; start < len(targets); start += size {
|
||||
// end 是当前分片结束下标。
|
||||
end := start + size
|
||||
if end > len(targets) {
|
||||
end = len(targets)
|
||||
}
|
||||
chunks = append(chunks, targets[start:end])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -377,618 +375,3 @@ func (m *Manager) InitializeContext(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// detectBrowserFingerprint 封装detect浏览器Fingerprint业务协调。
|
||||
func (m *Manager) detectBrowserFingerprint() error {
|
||||
// observed 用于本次流程后续判断的observed
|
||||
observed := make(chan http.Header, 1)
|
||||
// server 用于本次流程后续判断的server
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
observed <- r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write([]byte("<!doctype html><title>fingerprint</title>"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = b.Close() }()
|
||||
// ctx、err 用于本次流程后续判断的ctx、err
|
||||
ctx, err := b.NewContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = ctx.Close() }()
|
||||
// page、err 用于本次流程后续判断的page、err
|
||||
page, err := ctx.NewPage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
return err
|
||||
}
|
||||
// headers 用于本次流程后续判断的headers
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-observed:
|
||||
case <-time.After(5 * time.Second):
|
||||
return fmt.Errorf("等待 Chromium 指纹请求超时")
|
||||
}
|
||||
if strings.TrimSpace(headers.Get("User-Agent")) == "" {
|
||||
return fmt.Errorf("Chromium 返回空 userAgent")
|
||||
}
|
||||
// metadata 是本次实测 Chromium 的高熵 Client Hints;err 表示页面未暴露或无法读取该浏览器信息。
|
||||
metadata, err := readUserAgentMetadata(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err)
|
||||
}
|
||||
// fingerprint 是去除无头产品标记后的运行时身份,供后续无头页面和协议请求一致使用。
|
||||
fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
UserAgent: headers.Get("User-Agent"),
|
||||
SecChUA: headers.Get("sec-ch-ua"),
|
||||
Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`),
|
||||
Mobile: headers.Get("sec-ch-ua-mobile"),
|
||||
})
|
||||
m.browserFingerprint = fingerprint
|
||||
m.userAgentMetadata = normalizeUserAgentMetadata(metadata)
|
||||
xianyu.SetBrowserFingerprint(fingerprint)
|
||||
m.logger.Info("已读取 Playwright Chromium 浏览器指纹", "browser_version", b.Version(), "user_agent", fingerprint.UserAgent, "headless_token_removed", fingerprint.UserAgent != headers.Get("User-Agent"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeBrowserFingerprint 移除 Chromium 无头模式附加的产品标记,同时保留同一运行时实测的版本和 Client Hints。
|
||||
func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint {
|
||||
fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent)
|
||||
fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA)
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
// normalizeHeadlessUserAgent 只替换 UA 中的 HeadlessChrome 产品名,避免伪造浏览器版本、平台或其他身份字段。
|
||||
func normalizeHeadlessUserAgent(userAgent string) string {
|
||||
return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/")
|
||||
}
|
||||
|
||||
// normalizeSecChUA 规范化 Sec-CH-UA 品牌并按品牌去重,保证无头标记不会通过 Client Hints 泄露。
|
||||
func normalizeSecChUA(value string) string {
|
||||
// parts 是按逗号拆分的原始品牌条目,保留同一 Chromium 实测版本字段。
|
||||
parts := strings.Split(value, ",")
|
||||
// result 以原始顺序收集保留后的品牌条目;seen 防止替换 HeadlessChrome 后的重复品牌。
|
||||
result := make([]string, 0, len(parts))
|
||||
// seen 按规范化品牌名去重,避免同一产品经替换后重复出现在请求头。
|
||||
seen := make(map[string]struct{}, len(parts))
|
||||
// part 是当前待规范化的 Sec-CH-UA 品牌条目。
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium"))
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
// brand 是用于去重的品牌名,不含版本参数。
|
||||
brand := part
|
||||
// index 是品牌名与版本参数分隔分号的位置,负值表示条目没有参数。
|
||||
if index := strings.IndexByte(brand, ';'); index >= 0 {
|
||||
brand = strings.TrimSpace(brand[:index])
|
||||
}
|
||||
// exists 表示同名品牌已被保留,避免 HeadlessChrome 归一化后出现重复条目。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
result = append(result, part)
|
||||
}
|
||||
return strings.Join(result, ", ")
|
||||
}
|
||||
|
||||
// readUserAgentMetadata 从页面读取 Chromium 公开的低、高熵 Client Hints,返回可传给 CDP 的对象或读取失败原因。
|
||||
func readUserAgentMetadata(page playwright.Page) (map[string]any, error) {
|
||||
// value 是页面脚本返回的任意值;err 表示浏览器脚本执行或高熵字段读取失败。
|
||||
value, err := page.Evaluate(`async () => {
|
||||
const data = navigator.userAgentData;
|
||||
if (!data) return null;
|
||||
const high = await data.getHighEntropyValues([
|
||||
'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64'
|
||||
]);
|
||||
return {
|
||||
brands: data.brands,
|
||||
fullVersionList: high.fullVersionList,
|
||||
platform: data.platform,
|
||||
platformVersion: high.platformVersion,
|
||||
architecture: high.architecture,
|
||||
model: high.model,
|
||||
mobile: data.mobile,
|
||||
bitness: high.bitness,
|
||||
wow64: high.wow64
|
||||
};
|
||||
}`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 不可用")
|
||||
}
|
||||
// metadata 是可作为 CDP userAgentMetadata 使用的对象;ok 证明脚本结果的结构正确。
|
||||
metadata, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value)
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// normalizeUserAgentMetadata 复制 Client Hints 并仅规范化品牌列表,避免修改 Manager 持有的实测元数据。
|
||||
func normalizeUserAgentMetadata(metadata map[string]any) map[string]any {
|
||||
if len(metadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
// result 是供当前页面 CDP 覆盖使用的独立元数据副本。
|
||||
result := make(map[string]any, len(metadata))
|
||||
// key 是当前 Client Hints 字段名;value 是其待复制或规范化的值。
|
||||
for key, value := range metadata {
|
||||
switch key {
|
||||
case "brands", "fullVersionList":
|
||||
result[key] = normalizeUserAgentBrands(value)
|
||||
default:
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// normalizeUserAgentBrands 将品牌列表中的无头标记替换为 Chromium,并按品牌保留首个实测版本条目。
|
||||
func normalizeUserAgentBrands(value any) []any {
|
||||
// brands 是页面返回的品牌数组;ok 表示该字段可以安全按数组处理。
|
||||
brands, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// result 收集归一化后的品牌对象;seen 防止别名替换后的品牌重复。
|
||||
result := make([]any, 0, len(brands))
|
||||
// seen 记录已经保留的规范化品牌名,保证 CDP metadata 与 Sec-CH-UA 一致。
|
||||
seen := make(map[string]struct{}, len(brands))
|
||||
// item 是当前页面返回的候选品牌对象。
|
||||
for _, item := range brands {
|
||||
// brandEntry 是转换后的品牌对象;ok 表示候选条目有可读取字段。
|
||||
brandEntry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// brand 是去重和覆盖写回使用的产品名,非字符串字段按空值丢弃。
|
||||
brand, _ := brandEntry["brand"].(string)
|
||||
brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium")
|
||||
if brand == "" {
|
||||
continue
|
||||
}
|
||||
// exists 表示相同规范化品牌已经收录。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
// entry 是独立拷贝,防止更改本次页面覆盖时改写原始实测对象。
|
||||
entry := make(map[string]any, len(brandEntry))
|
||||
// key 是当前品牌字段名;itemValue 是需原样保留的版本等字段。
|
||||
for key, itemValue := range brandEntry {
|
||||
entry[key] = itemValue
|
||||
}
|
||||
entry["brand"] = brand
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// headlessUserAgent 返回当前实测 Chromium 的规范化无头 UA;未完成指纹探测时回退全局实测值,仍不可用则返回 nil。
|
||||
func (m *Manager) headlessUserAgent() *string {
|
||||
// userAgent 是移除 HeadlessChrome 标记后的 runtime UA,保持版本与协议侧指纹一致。
|
||||
userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent)
|
||||
if userAgent == "" {
|
||||
userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent)
|
||||
}
|
||||
if userAgent == "" {
|
||||
return nil
|
||||
}
|
||||
return playwright.String(userAgent)
|
||||
}
|
||||
|
||||
// newBrowserPage 从 bctx 创建页面;无头模式会在首次导航前应用 UA/Client Hints 覆盖,失败时关闭半成品页面并返回错误。
|
||||
func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) {
|
||||
// page 是新建的浏览器页面;err 表示 context 不可用或页面创建失败。
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !headless {
|
||||
return page, nil
|
||||
}
|
||||
// err 表示页面级 CDP 指纹覆盖失败,不能继续导航以免暴露无头身份。
|
||||
if err := m.applyHeadlessFingerprint(page); err != nil {
|
||||
_ = page.Close()
|
||||
return nil, err
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// applyHeadlessFingerprint 通过页面级 CDP 在首次导航前覆盖 UA 与 Client Hints;成功后故意保持会话附着以维持页面身份。
|
||||
func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error {
|
||||
// userAgent 是当前运行时的规范化 UA,nil 表示未完成必须的初始化探测。
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
return fmt.Errorf("无头 Chromium User-Agent 未初始化")
|
||||
}
|
||||
// metadata 是可安全传给当前页面的 Client Hints 拷贝,不能含 HeadlessChrome 品牌。
|
||||
metadata := normalizeUserAgentMetadata(m.userAgentMetadata)
|
||||
if len(metadata) == 0 {
|
||||
return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化")
|
||||
}
|
||||
// session 是页面生命周期内保持附着的 CDP 会话;err 表示 Chromium 拒绝创建目标会话。
|
||||
session, err := page.Context().NewCDPSession(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err)
|
||||
}
|
||||
// err 表示 Chromium 未接受身份覆盖;此时立即分离 session 防止资源泄漏。
|
||||
if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{
|
||||
"userAgent": *userAgent,
|
||||
"userAgentMetadata": metadata,
|
||||
}); err != nil {
|
||||
_ = session.Detach()
|
||||
return fmt.Errorf("应用 Chromium 无头指纹: %w", err)
|
||||
}
|
||||
// session 在 page 生命周期内必须保持附着;目标级仿真会话分离后 Chromium 会还原 navigator.userAgentData。
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 释放所有浏览器与 Playwright;它会等待活动实例退出且不会遗留关闭 goroutine。
|
||||
func (m *Manager) Close() error {
|
||||
// closeCtx、closeCancel 为兼容入口提供有限关闭预算,避免同步 Playwright 释放永久阻塞调用方。
|
||||
closeCtx, closeCancel := context.WithTimeout(context.Background(), legacyLifecycleOperationTimeout)
|
||||
defer closeCancel()
|
||||
return m.CloseContext(closeCtx)
|
||||
}
|
||||
|
||||
// CloseContext 拒绝新调用并等待已有浏览器调用结束后同步释放资源。
|
||||
// ctx 到期时返回 ctx.Err,管理器保持 closing 状态,调用方可稍后用更长的 Context 重试;
|
||||
// 实现不通过后台 goroutine 包装 Close,因此超时不会留下无法观察的关闭任务。
|
||||
func (m *Manager) CloseContext(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return errors.New("关闭浏览器需要调用方 Context")
|
||||
}
|
||||
// err 表示调用方在关闭开始前已经取消等待,管理器保持可重试状态。
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.closeMu.Lock()
|
||||
defer m.closeMu.Unlock()
|
||||
m.ensureLifecycleCond()
|
||||
m.lifecycleMu.Lock()
|
||||
if m.closed {
|
||||
m.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
m.closing = true
|
||||
m.lifecycleMu.Unlock()
|
||||
|
||||
// 轮询等待而不是把条件等待放进 goroutine,以便 Context 取消时没有游离任务。
|
||||
for {
|
||||
m.lifecycleMu.Lock()
|
||||
// remaining 表示仍持有浏览器实例或上下文的活动调用数量。
|
||||
remaining := m.inFlight
|
||||
m.lifecycleMu.Unlock()
|
||||
if remaining == 0 {
|
||||
break
|
||||
}
|
||||
// waitTimer 限制单次轮询间隔,避免为 Context 等待启动后台 goroutine。
|
||||
waitTimer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !waitTimer.Stop() {
|
||||
<-waitTimer.C
|
||||
}
|
||||
return ctx.Err()
|
||||
case <-waitTimer.C:
|
||||
}
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
// entries 用于本次流程后续判断的entries
|
||||
entries := make([]*poolEntry, 0, len(m.pool))
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range m.pool {
|
||||
entries = append(entries, e)
|
||||
}
|
||||
m.pool = make(map[string]*poolEntry)
|
||||
m.mu.Unlock()
|
||||
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range entries {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
// stopErr 保存 Playwright 进程同步停止时返回的错误。
|
||||
var stopErr error
|
||||
if m.pw != nil {
|
||||
stopErr = m.pw.Stop()
|
||||
}
|
||||
m.lifecycleMu.Lock()
|
||||
m.closed = true
|
||||
m.lifecycleMu.Unlock()
|
||||
return stopErr
|
||||
}
|
||||
|
||||
// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。
|
||||
// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。
|
||||
// newPage 封装new页码业务协调。
|
||||
func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) {
|
||||
// err 表示管理器已关闭或调用方已取消,不能继续申请浏览器页。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// operationOnce 保证 page release 重复调用时只结束一次活动登记。
|
||||
var operationOnce sync.Once
|
||||
// finishOperation 在 page 释放或创建失败时结束生命周期登记。
|
||||
finishOperation := func() {
|
||||
operationOnce.Do(m.endOperation)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// entry、err 用于本次流程后续判断的entry、err
|
||||
entry, err := m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// page 在无头模式下会在首次导航前收到运行时 UA 与 Client Hints 覆盖。
|
||||
page, err := m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
// context 损坏,丢弃重建一次。
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
entry, err = m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
page, err = m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
finishOperation()
|
||||
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// release 用于本次流程后续判断的release
|
||||
release := func() {
|
||||
_ = page.Close()
|
||||
m.releaseEntry(cookieID, entry)
|
||||
finishOperation()
|
||||
}
|
||||
return page, release, nil
|
||||
}
|
||||
|
||||
// acquireEntry 封装acquireEntry业务协调。
|
||||
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.claimEntryLocked(e)
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// created、err 用于本次流程后续判断的created、err
|
||||
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// 池满,淘汰最久未用。
|
||||
m.evictIfNeeded()
|
||||
return m.createEntry(cookieID, cookieStr, headless)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// entry、ok 用于本次流程后续判断的entry、ok
|
||||
entry, ok := created.(*poolEntry)
|
||||
if !ok || entry == nil {
|
||||
return nil, fmt.Errorf("浏览器池创建返回异常")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current == entry {
|
||||
m.claimEntryLocked(entry)
|
||||
m.mu.Unlock()
|
||||
} else {
|
||||
m.mu.Unlock()
|
||||
return nil, fmt.Errorf("浏览器池条目在获取期间已失效")
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// claimEntryLocked 封装claimEntryLocked业务协调。
|
||||
func (m *Manager) claimEntryLocked(entry *poolEntry) {
|
||||
entry.lastUsed = time.Now()
|
||||
if entry.initialLeaseAvailable {
|
||||
entry.initialLeaseAvailable = false
|
||||
return
|
||||
}
|
||||
entry.active++
|
||||
}
|
||||
|
||||
// releaseEntry 封装releaseEntry业务协调。
|
||||
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current != entry {
|
||||
return
|
||||
}
|
||||
if entry.active > 0 {
|
||||
entry.active--
|
||||
}
|
||||
entry.lastUsed = time.Now()
|
||||
}
|
||||
|
||||
// createEntry 封装createEntry业务协调。
|
||||
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
// browser、err 用于本次流程后续判断的browser、err
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
// contextOptions 保留 Chromium 原生上下文配置;无头 UA 仅使用本次实测 runtime 的规范化版本。
|
||||
contextOptions := playwright.BrowserNewContextOptions{
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
}
|
||||
if headless {
|
||||
contextOptions.UserAgent = m.headlessUserAgent()
|
||||
}
|
||||
// context 是 browser 的新隔离上下文;err 表示 context 创建失败并触发已启动浏览器回收。
|
||||
context, err := browser.NewContext(contextOptions)
|
||||
if err != nil {
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if cookieStr != "" {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := addCookieStr(context, cookieStr); err != nil {
|
||||
_ = context.Close()
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("注入 cookie 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// entry 用于本次流程后续判断的entry
|
||||
entry := &poolEntry{
|
||||
cookieID: cookieID,
|
||||
browser: browser,
|
||||
context: context,
|
||||
lastUsed: time.Now(),
|
||||
active: 1,
|
||||
initialLeaseAvailable: true,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.pool[cookieID] = entry
|
||||
m.mu.Unlock()
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// touch 封装touch业务协调。
|
||||
func (m *Manager) touch(cookieID string) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok {
|
||||
e.lastUsed = time.Now()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// evict 封装evict业务协调。
|
||||
func (m *Manager) evict(cookieID string) {
|
||||
m.mu.Lock()
|
||||
// e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]
|
||||
if ok && e.active > 0 {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(m.pool, cookieID)
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// evictIfNeeded 封装evictIfNeeded业务协调。
|
||||
func (m *Manager) evictIfNeeded() {
|
||||
m.mu.Lock()
|
||||
if len(m.pool) < m.maxSize {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// oldest 用于本次流程后续判断的oldest
|
||||
var oldest *poolEntry
|
||||
// oldestID 用于本次流程后续判断的oldestID
|
||||
var oldestID string
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
if e.active > 0 {
|
||||
continue
|
||||
}
|
||||
if oldest == nil || e.lastUsed.Before(oldest.lastUsed) {
|
||||
oldest = e
|
||||
oldestID = id
|
||||
}
|
||||
}
|
||||
if oldest != nil {
|
||||
delete(m.pool, oldestID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if oldest != nil {
|
||||
closeEntry(oldest, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// CleanupIdle 清理超过 idleTTL 未用的浏览器。
|
||||
func (m *Manager) CleanupIdle() {
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now()
|
||||
m.mu.Lock()
|
||||
// toClose 用于本次流程后续判断的toClose
|
||||
var toClose []*poolEntry
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
|
||||
toClose = append(toClose, e)
|
||||
delete(m.pool, id)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range toClose {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// closeEntry 封装closeEntry业务协调。
|
||||
func closeEntry(e *poolEntry, logger *slog.Logger) {
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
if e.context != nil {
|
||||
_ = e.context.Close()
|
||||
}
|
||||
if e.browser != nil {
|
||||
_ = e.browser.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// addCookieStr 把 "k=v; k2=v2" 注入 context(domain .goofish.com)。
|
||||
func addCookieStr(ctx playwright.BrowserContext, cookieStr string) error {
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
cookies := parseCookieStrToPlaywright(cookieStr)
|
||||
if len(cookies) == 0 {
|
||||
return errors.New("cookie 为空或格式错误")
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := ctx.ClearCookies(); err != nil {
|
||||
return fmt.Errorf("清理浏览器旧 cookie: %w", err)
|
||||
}
|
||||
return ctx.AddCookies(cookies)
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
// detectBrowserFingerprint 从受控 Chromium 读取运行时指纹,供浏览器与非浏览器协议请求统一使用。
|
||||
func (m *Manager) detectBrowserFingerprint() error {
|
||||
// observed 用于本次流程后续判断的observed
|
||||
observed := make(chan http.Header, 1)
|
||||
// server 用于本次流程后续判断的server
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
observed <- r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write([]byte("<!doctype html><title>fingerprint</title>"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = b.Close() }()
|
||||
// ctx、err 用于本次流程后续判断的ctx、err
|
||||
ctx, err := b.NewContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = ctx.Close() }()
|
||||
// page、err 用于本次流程后续判断的page、err
|
||||
page, err := ctx.NewPage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
return err
|
||||
}
|
||||
// headers 用于本次流程后续判断的headers
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-observed:
|
||||
case <-time.After(5 * time.Second):
|
||||
return fmt.Errorf("等待 Chromium 指纹请求超时")
|
||||
}
|
||||
if strings.TrimSpace(headers.Get("User-Agent")) == "" {
|
||||
return fmt.Errorf("Chromium 返回空 userAgent")
|
||||
}
|
||||
// metadata 是本次实测 Chromium 的高熵 Client Hints;err 表示页面未暴露或无法读取该浏览器信息。
|
||||
metadata, err := readUserAgentMetadata(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err)
|
||||
}
|
||||
// fingerprint 是去除无头产品标记后的运行时身份,供后续无头页面和协议请求一致使用。
|
||||
fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
UserAgent: headers.Get("User-Agent"),
|
||||
SecChUA: headers.Get("sec-ch-ua"),
|
||||
Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`),
|
||||
Mobile: headers.Get("sec-ch-ua-mobile"),
|
||||
})
|
||||
m.browserFingerprint = fingerprint
|
||||
m.userAgentMetadata = normalizeUserAgentMetadata(metadata)
|
||||
xianyu.SetBrowserFingerprint(fingerprint)
|
||||
m.logger.Info("已读取 Playwright Chromium 浏览器指纹", "browser_version", b.Version(), "user_agent", fingerprint.UserAgent, "headless_token_removed", fingerprint.UserAgent != headers.Get("User-Agent"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeBrowserFingerprint 移除 Chromium 无头模式附加的产品标记,同时保留同一运行时实测的版本和 Client Hints。
|
||||
func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint {
|
||||
fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent)
|
||||
fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA)
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
// normalizeHeadlessUserAgent 只替换 UA 中的 HeadlessChrome 产品名,避免伪造浏览器版本、平台或其他身份字段。
|
||||
func normalizeHeadlessUserAgent(userAgent string) string {
|
||||
return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/")
|
||||
}
|
||||
|
||||
// normalizeSecChUA 规范化 Sec-CH-UA 品牌并按品牌去重,保证无头标记不会通过 Client Hints 泄露。
|
||||
func normalizeSecChUA(value string) string {
|
||||
// parts 是按逗号拆分的原始品牌条目,保留同一 Chromium 实测版本字段。
|
||||
parts := strings.Split(value, ",")
|
||||
// result 以原始顺序收集保留后的品牌条目;seen 防止替换 HeadlessChrome 后的重复品牌。
|
||||
result := make([]string, 0, len(parts))
|
||||
// seen 按规范化品牌名去重,避免同一产品经替换后重复出现在请求头。
|
||||
seen := make(map[string]struct{}, len(parts))
|
||||
// part 是当前待规范化的 Sec-CH-UA 品牌条目。
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium"))
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
// brand 是用于去重的品牌名,不含版本参数。
|
||||
brand := part
|
||||
// index 是品牌名与版本参数分隔分号的位置,负值表示条目没有参数。
|
||||
if index := strings.IndexByte(brand, ';'); index >= 0 {
|
||||
brand = strings.TrimSpace(brand[:index])
|
||||
}
|
||||
// exists 表示同名品牌已被保留,避免 HeadlessChrome 归一化后出现重复条目。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
result = append(result, part)
|
||||
}
|
||||
return strings.Join(result, ", ")
|
||||
}
|
||||
|
||||
// readUserAgentMetadata 从页面读取 Chromium 公开的低、高熵 Client Hints,返回可传给 CDP 的对象或读取失败原因。
|
||||
func readUserAgentMetadata(page playwright.Page) (map[string]any, error) {
|
||||
// value 是页面脚本返回的任意值;err 表示浏览器脚本执行或高熵字段读取失败。
|
||||
value, err := page.Evaluate(`async () => {
|
||||
const data = navigator.userAgentData;
|
||||
if (!data) return null;
|
||||
const high = await data.getHighEntropyValues([
|
||||
'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64'
|
||||
]);
|
||||
return {
|
||||
brands: data.brands,
|
||||
fullVersionList: high.fullVersionList,
|
||||
platform: data.platform,
|
||||
platformVersion: high.platformVersion,
|
||||
architecture: high.architecture,
|
||||
model: high.model,
|
||||
mobile: data.mobile,
|
||||
bitness: high.bitness,
|
||||
wow64: high.wow64
|
||||
};
|
||||
}`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 不可用")
|
||||
}
|
||||
// metadata 是可作为 CDP userAgentMetadata 使用的对象;ok 证明脚本结果的结构正确。
|
||||
metadata, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value)
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// normalizeUserAgentMetadata 复制 Client Hints 并仅规范化品牌列表,避免修改 Manager 持有的实测元数据。
|
||||
func normalizeUserAgentMetadata(metadata map[string]any) map[string]any {
|
||||
if len(metadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
// result 是供当前页面 CDP 覆盖使用的独立元数据副本。
|
||||
result := make(map[string]any, len(metadata))
|
||||
// key 是当前 Client Hints 字段名;value 是其待复制或规范化的值。
|
||||
for key, value := range metadata {
|
||||
switch key {
|
||||
case "brands", "fullVersionList":
|
||||
result[key] = normalizeUserAgentBrands(value)
|
||||
default:
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// normalizeUserAgentBrands 将品牌列表中的无头标记替换为 Chromium,并按品牌保留首个实测版本条目。
|
||||
func normalizeUserAgentBrands(value any) []any {
|
||||
// brands 是页面返回的品牌数组;ok 表示该字段可以安全按数组处理。
|
||||
brands, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// result 收集归一化后的品牌对象;seen 防止别名替换后的品牌重复。
|
||||
result := make([]any, 0, len(brands))
|
||||
// seen 记录已经保留的规范化品牌名,保证 CDP metadata 与 Sec-CH-UA 一致。
|
||||
seen := make(map[string]struct{}, len(brands))
|
||||
// item 是当前页面返回的候选品牌对象。
|
||||
for _, item := range brands {
|
||||
// brandEntry 是转换后的品牌对象;ok 表示候选条目有可读取字段。
|
||||
brandEntry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// brand 是去重和覆盖写回使用的产品名,非字符串字段按空值丢弃。
|
||||
brand, _ := brandEntry["brand"].(string)
|
||||
brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium")
|
||||
if brand == "" {
|
||||
continue
|
||||
}
|
||||
// exists 表示相同规范化品牌已经收录。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
// entry 是独立拷贝,防止更改本次页面覆盖时改写原始实测对象。
|
||||
entry := make(map[string]any, len(brandEntry))
|
||||
// key 是当前品牌字段名;itemValue 是需原样保留的版本等字段。
|
||||
for key, itemValue := range brandEntry {
|
||||
entry[key] = itemValue
|
||||
}
|
||||
entry["brand"] = brand
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// headlessUserAgent 返回当前实测 Chromium 的规范化无头 UA;未完成指纹探测时回退全局实测值,仍不可用则返回 nil。
|
||||
func (m *Manager) headlessUserAgent() *string {
|
||||
// userAgent 是移除 HeadlessChrome 标记后的 runtime UA,保持版本与协议侧指纹一致。
|
||||
userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent)
|
||||
if userAgent == "" {
|
||||
userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent)
|
||||
}
|
||||
if userAgent == "" {
|
||||
return nil
|
||||
}
|
||||
return playwright.String(userAgent)
|
||||
}
|
||||
|
||||
// newBrowserPage 从 bctx 创建页面;无头模式会在首次导航前应用 UA/Client Hints 覆盖,失败时关闭半成品页面并返回错误。
|
||||
func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) {
|
||||
// page 是新建的浏览器页面;err 表示 context 不可用或页面创建失败。
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !headless {
|
||||
return page, nil
|
||||
}
|
||||
// err 表示页面级 CDP 指纹覆盖失败,不能继续导航以免暴露无头身份。
|
||||
if err := m.applyHeadlessFingerprint(page); err != nil {
|
||||
_ = page.Close()
|
||||
return nil, err
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// applyHeadlessFingerprint 通过页面级 CDP 在首次导航前覆盖 UA 与 Client Hints;成功后故意保持会话附着以维持页面身份。
|
||||
func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error {
|
||||
// userAgent 是当前运行时的规范化 UA,nil 表示未完成必须的初始化探测。
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
return fmt.Errorf("无头 Chromium User-Agent 未初始化")
|
||||
}
|
||||
// metadata 是可安全传给当前页面的 Client Hints 拷贝,不能含 HeadlessChrome 品牌。
|
||||
metadata := normalizeUserAgentMetadata(m.userAgentMetadata)
|
||||
if len(metadata) == 0 {
|
||||
return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化")
|
||||
}
|
||||
// session 是页面生命周期内保持附着的 CDP 会话;err 表示 Chromium 拒绝创建目标会话。
|
||||
session, err := page.Context().NewCDPSession(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err)
|
||||
}
|
||||
// err 表示 Chromium 未接受身份覆盖;此时立即分离 session 防止资源泄漏。
|
||||
if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{
|
||||
"userAgent": *userAgent,
|
||||
"userAgentMetadata": metadata,
|
||||
}); err != nil {
|
||||
_ = session.Detach()
|
||||
return fmt.Errorf("应用 Chromium 无头指纹: %w", err)
|
||||
}
|
||||
// session 在 page 生命周期内必须保持附着;目标级仿真会话分离后 Chromium 会还原 navigator.userAgentData。
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 释放所有浏览器与 Playwright;它会等待活动实例退出且不会遗留关闭 goroutine。
|
||||
func (m *Manager) Close() error {
|
||||
// closeCtx、closeCancel 为兼容入口提供有限关闭预算,避免同步 Playwright 释放永久阻塞调用方。
|
||||
closeCtx, closeCancel := context.WithTimeout(context.Background(), legacyLifecycleOperationTimeout)
|
||||
defer closeCancel()
|
||||
return m.CloseContext(closeCtx)
|
||||
}
|
||||
|
||||
// CloseContext 拒绝新调用并等待已有浏览器调用结束后同步释放资源。
|
||||
// ctx 到期时返回 ctx.Err,管理器保持 closing 状态,调用方可稍后用更长的 Context 重试;
|
||||
// 实现不通过后台 goroutine 包装 Close,因此超时不会留下无法观察的关闭任务。
|
||||
func (m *Manager) CloseContext(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return errors.New("关闭浏览器需要调用方 Context")
|
||||
}
|
||||
// err 表示调用方在关闭开始前已经取消等待,管理器保持可重试状态。
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.closeMu.Lock()
|
||||
defer m.closeMu.Unlock()
|
||||
m.ensureLifecycleCond()
|
||||
m.lifecycleMu.Lock()
|
||||
if m.closed {
|
||||
m.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
m.closing = true
|
||||
m.lifecycleMu.Unlock()
|
||||
|
||||
// 轮询等待而不是把条件等待放进 goroutine,以便 Context 取消时没有游离任务。
|
||||
for {
|
||||
m.lifecycleMu.Lock()
|
||||
// remaining 表示仍持有浏览器实例或上下文的活动调用数量。
|
||||
remaining := m.inFlight
|
||||
m.lifecycleMu.Unlock()
|
||||
if remaining == 0 {
|
||||
break
|
||||
}
|
||||
// waitTimer 限制单次轮询间隔,避免为 Context 等待启动后台 goroutine。
|
||||
waitTimer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !waitTimer.Stop() {
|
||||
<-waitTimer.C
|
||||
}
|
||||
return ctx.Err()
|
||||
case <-waitTimer.C:
|
||||
}
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
// entries 用于本次流程后续判断的entries
|
||||
entries := make([]*poolEntry, 0, len(m.pool))
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range m.pool {
|
||||
entries = append(entries, e)
|
||||
}
|
||||
m.pool = make(map[string]*poolEntry)
|
||||
m.mu.Unlock()
|
||||
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range entries {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
// stopErr 保存 Playwright 进程同步停止时返回的错误。
|
||||
var stopErr error
|
||||
if m.pw != nil {
|
||||
stopErr = m.pw.Stop()
|
||||
}
|
||||
m.lifecycleMu.Lock()
|
||||
m.closed = true
|
||||
m.lifecycleMu.Unlock()
|
||||
return stopErr
|
||||
}
|
||||
|
||||
// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。
|
||||
// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。
|
||||
// newPage 封装new页码业务协调。
|
||||
func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) {
|
||||
// err 表示管理器已关闭或调用方已取消,不能继续申请浏览器页。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// operationOnce 保证 page release 重复调用时只结束一次活动登记。
|
||||
var operationOnce sync.Once
|
||||
// finishOperation 在 page 释放或创建失败时结束生命周期登记。
|
||||
finishOperation := func() {
|
||||
operationOnce.Do(m.endOperation)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// entry、err 用于本次流程后续判断的entry、err
|
||||
entry, err := m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// page 在无头模式下会在首次导航前收到运行时 UA 与 Client Hints 覆盖。
|
||||
page, err := m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
// context 损坏,丢弃重建一次。
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
entry, err = m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
page, err = m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
finishOperation()
|
||||
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// release 用于本次流程后续判断的release
|
||||
release := func() {
|
||||
_ = page.Close()
|
||||
m.releaseEntry(cookieID, entry)
|
||||
finishOperation()
|
||||
}
|
||||
return page, release, nil
|
||||
}
|
||||
|
||||
// acquireEntry 封装acquireEntry业务协调。
|
||||
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.claimEntryLocked(e)
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// created、err 用于本次流程后续判断的created、err
|
||||
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// 池满,淘汰最久未用。
|
||||
m.evictIfNeeded()
|
||||
return m.createEntry(cookieID, cookieStr, headless)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// entry、ok 用于本次流程后续判断的entry、ok
|
||||
entry, ok := created.(*poolEntry)
|
||||
if !ok || entry == nil {
|
||||
return nil, fmt.Errorf("浏览器池创建返回异常")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current == entry {
|
||||
m.claimEntryLocked(entry)
|
||||
m.mu.Unlock()
|
||||
} else {
|
||||
m.mu.Unlock()
|
||||
return nil, fmt.Errorf("浏览器池条目在获取期间已失效")
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// claimEntryLocked 封装claimEntryLocked业务协调。
|
||||
func (m *Manager) claimEntryLocked(entry *poolEntry) {
|
||||
entry.lastUsed = time.Now()
|
||||
if entry.initialLeaseAvailable {
|
||||
entry.initialLeaseAvailable = false
|
||||
return
|
||||
}
|
||||
entry.active++
|
||||
}
|
||||
|
||||
// releaseEntry 封装releaseEntry业务协调。
|
||||
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current != entry {
|
||||
return
|
||||
}
|
||||
if entry.active > 0 {
|
||||
entry.active--
|
||||
}
|
||||
entry.lastUsed = time.Now()
|
||||
}
|
||||
|
||||
// createEntry 封装createEntry业务协调。
|
||||
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
// browser、err 用于本次流程后续判断的browser、err
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
// contextOptions 保留 Chromium 原生上下文配置;无头 UA 仅使用本次实测 runtime 的规范化版本。
|
||||
contextOptions := playwright.BrowserNewContextOptions{
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
}
|
||||
if headless {
|
||||
contextOptions.UserAgent = m.headlessUserAgent()
|
||||
}
|
||||
// context 是 browser 的新隔离上下文;err 表示 context 创建失败并触发已启动浏览器回收。
|
||||
context, err := browser.NewContext(contextOptions)
|
||||
if err != nil {
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if cookieStr != "" {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := addCookieStr(context, cookieStr); err != nil {
|
||||
_ = context.Close()
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("注入 cookie 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// entry 用于本次流程后续判断的entry
|
||||
entry := &poolEntry{
|
||||
cookieID: cookieID,
|
||||
browser: browser,
|
||||
context: context,
|
||||
lastUsed: time.Now(),
|
||||
active: 1,
|
||||
initialLeaseAvailable: true,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.pool[cookieID] = entry
|
||||
m.mu.Unlock()
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// touch 封装touch业务协调。
|
||||
func (m *Manager) touch(cookieID string) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok {
|
||||
e.lastUsed = time.Now()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// evict 封装evict业务协调。
|
||||
func (m *Manager) evict(cookieID string) {
|
||||
m.mu.Lock()
|
||||
// e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]
|
||||
if ok && e.active > 0 {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(m.pool, cookieID)
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// evictIfNeeded 封装evictIfNeeded业务协调。
|
||||
func (m *Manager) evictIfNeeded() {
|
||||
m.mu.Lock()
|
||||
if len(m.pool) < m.maxSize {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// oldest 用于本次流程后续判断的oldest
|
||||
var oldest *poolEntry
|
||||
// oldestID 用于本次流程后续判断的oldestID
|
||||
var oldestID string
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
if e.active > 0 {
|
||||
continue
|
||||
}
|
||||
if oldest == nil || e.lastUsed.Before(oldest.lastUsed) {
|
||||
oldest = e
|
||||
oldestID = id
|
||||
}
|
||||
}
|
||||
if oldest != nil {
|
||||
delete(m.pool, oldestID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if oldest != nil {
|
||||
closeEntry(oldest, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// CleanupIdle 清理超过 idleTTL 未用的浏览器。
|
||||
func (m *Manager) CleanupIdle() {
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now()
|
||||
m.mu.Lock()
|
||||
// toClose 用于本次流程后续判断的toClose
|
||||
var toClose []*poolEntry
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
|
||||
toClose = append(toClose, e)
|
||||
delete(m.pool, id)
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range toClose {
|
||||
closeEntry(e, m.logger)
|
||||
}
|
||||
}
|
||||
|
||||
// closeEntry 封装closeEntry业务协调。
|
||||
func closeEntry(e *poolEntry, logger *slog.Logger) {
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
if e.context != nil {
|
||||
_ = e.context.Close()
|
||||
}
|
||||
if e.browser != nil {
|
||||
_ = e.browser.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// addCookieStr 把 "k=v; k2=v2" 注入 context(domain .goofish.com)。
|
||||
func addCookieStr(ctx playwright.BrowserContext, cookieStr string) error {
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
cookies := parseCookieStrToPlaywright(cookieStr)
|
||||
if len(cookies) == 0 {
|
||||
return errors.New("cookie 为空或格式错误")
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := ctx.ClearCookies(); err != nil {
|
||||
return fmt.Errorf("清理浏览器旧 cookie: %w", err)
|
||||
}
|
||||
return ctx.AddCookies(cookies)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// randomID 生成本地出站消息幂等键的随机后缀;随机源失败时使用时间回退避免阻断发送。
|
||||
func randomID() string {
|
||||
// value 保存随机读取的 128 位本地消息键熵。
|
||||
var value [16]byte
|
||||
// _, err 分别是随机字节读取数量和系统随机源错误。
|
||||
if _, err := rand.Read(value[:]); err == nil {
|
||||
return hex.EncodeToString(value[:])
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
|
||||
}
|
||||
|
||||
// extractString 在嵌套聊天载荷中按键名递归提取首个非空文本。
|
||||
func extractString(value any, keys ...string) string {
|
||||
// wanted 保存大小写无关的目标字段名。
|
||||
wanted := make(map[string]struct{}, len(keys))
|
||||
// key 是当前待规范化登记的目标字段名。
|
||||
for _, key := range keys {
|
||||
wanted[strings.ToLower(key)] = struct{}{}
|
||||
}
|
||||
// walk 递归处理对象、数组和可能嵌套 JSON 的字符串。
|
||||
var walk func(any) string
|
||||
walk = func(current any) string {
|
||||
// typed 是当前递归节点断言后的载荷容器类型。
|
||||
switch typed := current.(type) {
|
||||
case map[string]any:
|
||||
// key、child 分别是当前对象的字段名和字段值。
|
||||
for key, child := range typed {
|
||||
// ok 表示当前字段是否是调用方指定的候选字段。
|
||||
if _, ok := wanted[strings.ToLower(key)]; ok {
|
||||
// text 是转换并裁剪后的候选字段文本。
|
||||
if text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
// child 是当前对象中待递归查找的非目标字段值。
|
||||
for _, child := range typed {
|
||||
// text 是子树中返回的首个非空文本。
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 是当前数组中待递归查找的元素。
|
||||
for _, child := range typed {
|
||||
// text 是子元素中返回的首个非空文本。
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// decoded 是字符串形式 JSON 解码后的嵌套载荷。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(typed), &decoded) == nil {
|
||||
return walk(decoded)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
|
||||
// extractUnixMilli 提取聊天载荷的毫秒时间戳,并兼容秒级值。
|
||||
func extractUnixMilli(raw map[string]any) int64 {
|
||||
// text 是按平台候选字段读取的时间文本。
|
||||
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
|
||||
// value 是解析后的秒或毫秒 Unix 时间戳。
|
||||
var value int64
|
||||
_, _ = fmt.Sscan(text, &value)
|
||||
if value > 0 && value < 10_000_000_000 {
|
||||
value *= 1000
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
@@ -762,84 +761,3 @@ func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
// randomID 生成本地出站消息幂等键的随机后缀;随机源失败时使用时间回退避免阻断发送。
|
||||
func randomID() string {
|
||||
// value 用于本次流程后续判断的值
|
||||
var value [16]byte
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := rand.Read(value[:]); err == nil {
|
||||
return hex.EncodeToString(value[:])
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
|
||||
}
|
||||
|
||||
// extractString 封装extractString业务协调。
|
||||
func extractString(value any, keys ...string) string {
|
||||
// wanted 用于本次流程后续判断的wanted
|
||||
wanted := make(map[string]struct{}, len(keys))
|
||||
// key 表示当前遍历过程中的key
|
||||
for _, key := range keys {
|
||||
wanted[strings.ToLower(key)] = struct{}{}
|
||||
}
|
||||
// walk 用于本次流程后续判断的walk
|
||||
var walk func(any) string
|
||||
walk = func(v any) string {
|
||||
switch // x 用于本次流程后续判断的x
|
||||
x := v.(type) {
|
||||
case map[string]any:
|
||||
// key、child 表示当前遍历过程中的key、child
|
||||
for key, child := range x {
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := wanted[strings.ToLower(key)]; ok {
|
||||
if // text 用于本次流程后续判断的文本
|
||||
text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
// child 表示当前遍历过程中的child
|
||||
for _, child := range x {
|
||||
if // text 用于本次流程后续判断的文本
|
||||
text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 表示当前遍历过程中的child
|
||||
for _, child := range x {
|
||||
if // text 用于本次流程后续判断的文本
|
||||
text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// Live WS envelopes often keep extJson/bizTag as an encoded JSON
|
||||
// string. Decode it so messageId is preserved instead of falling
|
||||
// back to a local in-* key.
|
||||
// decoded 保存 extJson/bizTag 解码后的动态对象,供递归查找平台消息键。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
// text 保存递归命中的非空消息键,命中后立即返回避免生成本地回退键。
|
||||
if text := walk(decoded); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
|
||||
// extractUnixMilli 封装extractUnixMilli业务协调。
|
||||
func extractUnixMilli(raw map[string]any) int64 {
|
||||
// text 用于本次流程后续判断的文本
|
||||
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
|
||||
// value 用于本次流程后续判断的值
|
||||
var value int64
|
||||
_, _ = fmt.Sscan(text, &value)
|
||||
if value > 0 && value < 10_000_000_000 {
|
||||
value *= 1000
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -389,66 +389,10 @@ func New(dependencies Dependencies) (*Services, error) {
|
||||
if deleteErr != nil {
|
||||
return nil, fmt.Errorf("构造账号删除服务失败: %w", deleteErr)
|
||||
}
|
||||
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
|
||||
itemBatchPublish := dependencies.ItemDependencies.NewItemBatchPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
}, readBatchImageFile, downloadImageURL)
|
||||
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
|
||||
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
|
||||
dependencies.ItemDependencies.NewItemBatchRepository(),
|
||||
dependencies.ItemDependencies.NewItemCatalogRepository(),
|
||||
automationDependencies.NewAutomationRepository(),
|
||||
)
|
||||
if itemBatchLocalPublishErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布本地收口服务失败: %w", itemBatchLocalPublishErr)
|
||||
}
|
||||
// itemBatchPublisher、itemBatchPublisherErr 分别保存批量发布端口适配器及其组合期错误。
|
||||
itemBatchPublisher, itemBatchPublisherErr := adapter.NewItemBatchPublisher(itemBatchPublish, itemBatchLocalPublish)
|
||||
if itemBatchPublisherErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布 publisher 失败: %w", itemBatchPublisherErr)
|
||||
}
|
||||
// itemBatchRunner、batchRunnerErr 分别保存批量发布 worker 及其必需端口装配错误。
|
||||
itemBatchRunner, batchRunnerErr := adapter.NewItemBatchRunnerApplication(dependencies.ItemDependencies.NewItemBatchRepository(), itemBatchPublisher, publishBatchLease, publishBatchFailure)
|
||||
if batchRunnerErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布运行器失败: %w", batchRunnerErr)
|
||||
}
|
||||
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
|
||||
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
|
||||
dependencies.ItemDependencies.NewItemBatchRepository(),
|
||||
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
|
||||
)
|
||||
if batchRecoveryErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布恢复服务失败: %w", batchRecoveryErr)
|
||||
}
|
||||
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
|
||||
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
|
||||
OnWorkerError: func(batchID string, err error) {
|
||||
if dependencies.Logger != nil {
|
||||
dependencies.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err)
|
||||
}
|
||||
},
|
||||
OnRecoveryError: func(err error) {
|
||||
if dependencies.Logger != nil {
|
||||
dependencies.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
|
||||
}
|
||||
},
|
||||
})
|
||||
if batchCoordinatorErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布协调器失败: %w", batchCoordinatorErr)
|
||||
}
|
||||
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
|
||||
itemBatchPreviewPort := dependencies.ItemDependencies.NewItemBatchPreviewPort()
|
||||
// itemBatchPreview 是批量发布预检应用服务的构造结果。
|
||||
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
|
||||
if itemBatchPreviewErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布预检服务失败: %w", itemBatchPreviewErr)
|
||||
}
|
||||
// itemBatchManagement 是批次管理应用服务的构造结果。
|
||||
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(dependencies.ItemDependencies.NewItemBatchRepository(), adapter.NewBatchManagementRuntime(dependencies.LifecycleContext, itemBatchCoordinator))
|
||||
if itemBatchManagementErr != nil {
|
||||
return nil, fmt.Errorf("构造批量发布管理服务失败: %w", itemBatchManagementErr)
|
||||
// batchServices、batchServicesErr 分别是批量发布服务集合及其组合期错误。
|
||||
batchServices, batchServicesErr := buildItemBatchServices(dependencies, sessionRecovery, automationDependencies)
|
||||
if batchServicesErr != nil {
|
||||
return nil, batchServicesErr
|
||||
}
|
||||
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
|
||||
accountLoginCreate, accountLoginCreateErr := accountapp.NewLoginService(loginLifecycle)
|
||||
@@ -467,39 +411,10 @@ func New(dependencies Dependencies) (*Services, error) {
|
||||
}
|
||||
// qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。
|
||||
qrSessionRegistry := accountapp.NewQRLoginSessionRegistry()
|
||||
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
|
||||
itemCatalogRepository := dependencies.ItemDependencies.NewItemCatalogRepository()
|
||||
// itemCatalog 是商品列表和详情读取用例的应用服务。
|
||||
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
|
||||
if itemCatalogErr != nil {
|
||||
return nil, fmt.Errorf("构造商品目录服务失败: %w", itemCatalogErr)
|
||||
}
|
||||
// itemCatalogMutation 是商品写入用例的应用服务。
|
||||
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
|
||||
if itemCatalogMutationErr != nil {
|
||||
return nil, fmt.Errorf("构造商品目录写入服务失败: %w", itemCatalogMutationErr)
|
||||
}
|
||||
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
|
||||
itemPublishPort := dependencies.ItemDependencies.NewItemPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
|
||||
return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err)
|
||||
})
|
||||
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
|
||||
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
|
||||
if itemCategoryRecommendationErr != nil {
|
||||
return nil, fmt.Errorf("构造商品类目推荐服务失败: %w", itemCategoryRecommendationErr)
|
||||
}
|
||||
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
|
||||
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(dependencies.ItemDependencies.NewItemBatchRepository())
|
||||
if itemBatchPreviewPersistenceErr != nil {
|
||||
return nil, fmt.Errorf("构造批量预检持久化服务失败: %w", itemBatchPreviewPersistenceErr)
|
||||
}
|
||||
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
|
||||
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
|
||||
itemPublishPort,
|
||||
dependencies.ItemDependencies.NewItemPublishRepository(),
|
||||
)
|
||||
if itemSinglePublishErr != nil {
|
||||
return nil, fmt.Errorf("构造单商品发布服务失败: %w", itemSinglePublishErr)
|
||||
// catalogServices、catalogServicesErr 分别是商品目录服务集合及其组合期错误。
|
||||
catalogServices, catalogServicesErr := buildItemCatalogServices(dependencies, sessionRecovery)
|
||||
if catalogServicesErr != nil {
|
||||
return nil, catalogServicesErr
|
||||
}
|
||||
// services 是完成构造后只读注入 Server 的应用服务集合。
|
||||
services := &Services{
|
||||
@@ -508,20 +423,20 @@ func New(dependencies Dependencies) (*Services, error) {
|
||||
orders: orderServices,
|
||||
orderRefreshJobs: orderRefreshJobs,
|
||||
orderReconciliationRecovery: dependencies.OrderReconciliationRecovery,
|
||||
itemSinglePublish: itemSinglePublish,
|
||||
itemBatchCoordinator: itemBatchCoordinator,
|
||||
itemBatchPreview: itemBatchPreview,
|
||||
itemBatchManagement: itemBatchManagement,
|
||||
itemCategoryRecommendation: itemCategoryRecommendation,
|
||||
itemBatchPreviewPersistence: itemBatchPreviewPersistence,
|
||||
itemBatchLocalPublish: itemBatchLocalPublish,
|
||||
itemSinglePublish: catalogServices.singlePublish,
|
||||
itemBatchCoordinator: batchServices.coordinator,
|
||||
itemBatchPreview: batchServices.preview,
|
||||
itemBatchManagement: batchServices.management,
|
||||
itemCategoryRecommendation: catalogServices.categoryRecommendation,
|
||||
itemBatchPreviewPersistence: catalogServices.previewPersistence,
|
||||
itemBatchLocalPublish: batchServices.localPublish,
|
||||
itemSync: itemapp.NewSyncService(dependencies.ItemDependencies.NewItemSyncRepository(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
})),
|
||||
itemCatalog: itemCatalog,
|
||||
itemCatalogMutation: itemCatalogMutation,
|
||||
itemCatalog: catalogServices.catalog,
|
||||
itemCatalogMutation: catalogServices.mutation,
|
||||
accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry},
|
||||
authentication: nil,
|
||||
loginAudit: loginAudit,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package composition
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"xianyu-go/internal/adapter"
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
)
|
||||
|
||||
// itemBatchServices 是批量发布运行时、预检和本地收口服务的完整不可变组合结果。
|
||||
type itemBatchServices struct {
|
||||
// coordinator 拥有批量发布 worker 与恢复扫描生命周期。
|
||||
coordinator *itemapp.BatchWorkerCoordinator
|
||||
// preview 负责导入表格预检与图片校验。
|
||||
preview *itemapp.BatchPreviewService
|
||||
// management 负责批次查询、取消和重试用例。
|
||||
management *itemapp.BatchManagementService
|
||||
// localPublish 负责远端发布成功后的本地事务收口。
|
||||
localPublish *itemapp.BatchLocalPublishService
|
||||
}
|
||||
|
||||
// buildItemBatchServices 构造商品批量发布所需全部端口和后台组件,错误会阻止半初始化服务暴露。
|
||||
func buildItemBatchServices(dependencies Dependencies, sessionRecovery adapter.SessionRecoveryHandler, automationDependencies *adapter.AutomationDependencies) (itemBatchServices, error) {
|
||||
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
|
||||
itemBatchPublish := dependencies.ItemDependencies.NewItemBatchPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
}, readBatchImageFile, downloadImageURL)
|
||||
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
|
||||
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
|
||||
dependencies.ItemDependencies.NewItemBatchRepository(),
|
||||
dependencies.ItemDependencies.NewItemCatalogRepository(),
|
||||
automationDependencies.NewAutomationRepository(),
|
||||
)
|
||||
if itemBatchLocalPublishErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布本地收口服务失败: %w", itemBatchLocalPublishErr)
|
||||
}
|
||||
// itemBatchPublisher、itemBatchPublisherErr 分别保存批量发布端口适配器及其组合期错误。
|
||||
itemBatchPublisher, itemBatchPublisherErr := adapter.NewItemBatchPublisher(itemBatchPublish, itemBatchLocalPublish)
|
||||
if itemBatchPublisherErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布 publisher 失败: %w", itemBatchPublisherErr)
|
||||
}
|
||||
// itemBatchRunner、batchRunnerErr 分别保存批量发布 worker 及其必需端口装配错误。
|
||||
itemBatchRunner, batchRunnerErr := adapter.NewItemBatchRunnerApplication(dependencies.ItemDependencies.NewItemBatchRepository(), itemBatchPublisher, publishBatchLease, publishBatchFailure)
|
||||
if batchRunnerErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布运行器失败: %w", batchRunnerErr)
|
||||
}
|
||||
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
|
||||
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
|
||||
dependencies.ItemDependencies.NewItemBatchRepository(),
|
||||
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
|
||||
)
|
||||
if batchRecoveryErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布恢复服务失败: %w", batchRecoveryErr)
|
||||
}
|
||||
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
|
||||
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
|
||||
OnWorkerError: func(batchID string, err error) {
|
||||
if dependencies.Logger != nil {
|
||||
dependencies.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err)
|
||||
}
|
||||
},
|
||||
OnRecoveryError: func(err error) {
|
||||
if dependencies.Logger != nil {
|
||||
dependencies.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
|
||||
}
|
||||
},
|
||||
})
|
||||
if batchCoordinatorErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布协调器失败: %w", batchCoordinatorErr)
|
||||
}
|
||||
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
|
||||
itemBatchPreviewPort := dependencies.ItemDependencies.NewItemBatchPreviewPort()
|
||||
// itemBatchPreview 是批量发布预检应用服务的构造结果。
|
||||
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
|
||||
if itemBatchPreviewErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布预检服务失败: %w", itemBatchPreviewErr)
|
||||
}
|
||||
// itemBatchManagement 是批次管理应用服务的构造结果。
|
||||
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(dependencies.ItemDependencies.NewItemBatchRepository(), adapter.NewBatchManagementRuntime(dependencies.LifecycleContext, itemBatchCoordinator))
|
||||
if itemBatchManagementErr != nil {
|
||||
return itemBatchServices{}, fmt.Errorf("构造批量发布管理服务失败: %w", itemBatchManagementErr)
|
||||
}
|
||||
return itemBatchServices{coordinator: itemBatchCoordinator, preview: itemBatchPreview, management: itemBatchManagement, localPublish: itemBatchLocalPublish}, nil
|
||||
}
|
||||
|
||||
// itemCatalogServices 是商品目录、发布和预检持久化服务的完整组合结果。
|
||||
type itemCatalogServices struct {
|
||||
// catalog 提供商品查询服务。
|
||||
catalog *itemapp.CatalogService
|
||||
// mutation 提供商品写入服务。
|
||||
mutation *itemapp.CatalogMutationService
|
||||
// categoryRecommendation 提供平台类目推荐服务。
|
||||
categoryRecommendation *itemapp.CategoryRecommendationService
|
||||
// previewPersistence 保存批量预检结果。
|
||||
previewPersistence *itemapp.BatchPreviewPersistenceService
|
||||
// singlePublish 提供单商品发布服务。
|
||||
singlePublish *itemapp.Service
|
||||
}
|
||||
|
||||
// buildItemCatalogServices 构造商品目录和发布服务,并把平台会话恢复回调限制在组合根。
|
||||
func buildItemCatalogServices(dependencies Dependencies, sessionRecovery adapter.SessionRecoveryHandler) (itemCatalogServices, error) {
|
||||
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
|
||||
itemCatalogRepository := dependencies.ItemDependencies.NewItemCatalogRepository()
|
||||
// itemCatalog 是商品列表和详情读取用例的应用服务。
|
||||
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
|
||||
if itemCatalogErr != nil {
|
||||
return itemCatalogServices{}, fmt.Errorf("构造商品目录服务失败: %w", itemCatalogErr)
|
||||
}
|
||||
// itemCatalogMutation 是商品写入用例的应用服务。
|
||||
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
|
||||
if itemCatalogMutationErr != nil {
|
||||
return itemCatalogServices{}, fmt.Errorf("构造商品目录写入服务失败: %w", itemCatalogMutationErr)
|
||||
}
|
||||
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
|
||||
itemPublishPort := dependencies.ItemDependencies.NewItemPublishPort(dependencies.MTopClient, dependencies.Logger, dependencies.UpdateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
|
||||
return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err)
|
||||
})
|
||||
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
|
||||
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
|
||||
if itemCategoryRecommendationErr != nil {
|
||||
return itemCatalogServices{}, fmt.Errorf("构造商品类目推荐服务失败: %w", itemCategoryRecommendationErr)
|
||||
}
|
||||
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
|
||||
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(dependencies.ItemDependencies.NewItemBatchRepository())
|
||||
if itemBatchPreviewPersistenceErr != nil {
|
||||
return itemCatalogServices{}, fmt.Errorf("构造批量预检持久化服务失败: %w", itemBatchPreviewPersistenceErr)
|
||||
}
|
||||
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
|
||||
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
|
||||
itemPublishPort,
|
||||
dependencies.ItemDependencies.NewItemPublishRepository(),
|
||||
)
|
||||
if itemSinglePublishErr != nil {
|
||||
return itemCatalogServices{}, fmt.Errorf("构造单商品发布服务失败: %w", itemSinglePublishErr)
|
||||
}
|
||||
return itemCatalogServices{catalog: itemCatalog, mutation: itemCatalogMutation, categoryRecommendation: itemCategoryRecommendation, previewPersistence: itemBatchPreviewPersistence, singlePublish: itemSinglePublish}, nil
|
||||
}
|
||||
@@ -3,9 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -782,524 +780,3 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
|
||||
// 结果不确定的求评价运行。这些记录 sent_count=0,且错误明确发生在调用发送
|
||||
// 接口之前,可以安全清除 action_started 并进入现有失败重试流程。
|
||||
// RecoverDefinitelyUnsentReviewRuns 封装RecoverDefinitelyUnsentReview运行记录业务协调。
|
||||
func (a *AutomationRules) RecoverDefinitelyUnsentReviewRuns(ctx context.Context) (int64, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='failed',action_started=0,lease_expires_at=0,next_retry_at=0,
|
||||
error_message='历史版本在 WebSocket 就绪前执行,已恢复等待安全重试',
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE trigger_type='review_missing_timeout' AND status='needs_review' AND sent_count=0
|
||||
AND (error_message LIKE '%当前没有可用 WebSocket 连接%'
|
||||
OR error_message LIKE '%账号未在线,无法发送自动化消息%'
|
||||
OR error_message LIKE '%账号发送器未初始化%')`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// DeferTask 封装Defer任务业务协调。
|
||||
func (a *AutomationRules) DeferTask(ctx context.Context, task DeferredAutomationTask) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `INSERT INTO automation_pending_tasks
|
||||
(task_key,cookie_id,trigger_type,task_json,due_at,status,attempt_count,lease_expires_at,error_message)
|
||||
VALUES (?,?,?,?,?,'pending',0,0,?)`+dialectUpsert(a.Dialect, []string{"task_key"}, map[string]string{
|
||||
"cookie_id": "excluded.cookie_id",
|
||||
"trigger_type": "excluded.trigger_type",
|
||||
"task_json": "excluded.task_json",
|
||||
"due_at": "excluded.due_at",
|
||||
"status": "'pending'",
|
||||
"attempt_count": "0",
|
||||
"lease_expires_at": "0",
|
||||
"error_message": "excluded.error_message",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt, task.ErrorMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListIssues 读取问题列表。
|
||||
func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]AutomationRunIssue, []DeferredAutomationIssue, error) {
|
||||
// runRows、err 用于本次流程后续判断的运行Rows、err
|
||||
runRows, err := a.DB.QueryContext(ctx, `SELECT ar.id,ar.cookie_id,ar.order_id,ar.trigger_type,ar.error_message,
|
||||
ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0)
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE c.user_id=? AND ar.status='needs_review' AND r.deleted_at IS NULL ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// runs 用于本次流程后续判断的运行记录
|
||||
runs := []AutomationRunIssue{}
|
||||
for runRows.Next() {
|
||||
// issue 用于本次流程后续判断的问题
|
||||
var issue AutomationRunIssue
|
||||
// rawEventJSON 用于本次流程后续判断的原始EventJSON
|
||||
var rawEventJSON string
|
||||
// actionStarted、ruleEnabled 用于本次流程后续判断的动作Started、rule启用状态
|
||||
var actionStarted, ruleEnabled int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := runRows.Scan(&issue.ID, &issue.CookieID, &issue.OrderID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.ActionCursor, &issue.SentCount, &issue.UpdatedAt, &rawEventJSON, &actionStarted, &ruleEnabled); err != nil {
|
||||
_ = runRows.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
issue.IssueKind, issue.AllowedResolutions = automationIssuePolicy(
|
||||
rawEventJSON, actionStarted != 0, ruleEnabled != 0, issue.SentCount, issue.ErrorMessage,
|
||||
)
|
||||
runs = append(runs, issue)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := runRows.Close(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// taskRows、err 用于本次流程后续判断的任务Rows、err
|
||||
taskRows, err := a.DB.QueryContext(ctx, `SELECT apt.id,apt.cookie_id,apt.trigger_type,apt.error_message,
|
||||
apt.attempt_count,apt.updated_at
|
||||
FROM automation_pending_tasks apt JOIN cookies c ON c.id=apt.cookie_id
|
||||
WHERE c.user_id=? AND apt.status='dead_letter' ORDER BY apt.updated_at DESC,apt.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer taskRows.Close()
|
||||
// tasks 用于本次流程后续判断的任务列表
|
||||
tasks := []DeferredAutomationIssue{}
|
||||
for taskRows.Next() {
|
||||
// issue 用于本次流程后续判断的问题
|
||||
var issue DeferredAutomationIssue
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := taskRows.Scan(&issue.ID, &issue.CookieID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.AttemptCount, &issue.UpdatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tasks = append(tasks, issue)
|
||||
}
|
||||
return runs, tasks, taskRows.Err()
|
||||
}
|
||||
|
||||
// ResolveRunIssue 处理运行问题。
|
||||
func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error {
|
||||
// rawEventJSON、errorMessage 用于本次流程后续判断的原始EventJSON、error消息
|
||||
var rawEventJSON, errorMessage string
|
||||
// actionStarted、ruleEnabled、sentCount 用于本次流程后续判断的动作Started、ruleEnabled、sent数量
|
||||
var actionStarted, ruleEnabled, sentCount int
|
||||
// err 用于本次流程后续判断的err
|
||||
err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=? AND r.deleted_at IS NULL`, runID, userID).
|
||||
Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// allowed 用于本次流程后续判断的allowed
|
||||
_, allowed := automationIssuePolicy(rawEventJSON, actionStarted != 0, ruleEnabled != 0, sentCount, errorMessage)
|
||||
if !containsString(allowed, resolution) {
|
||||
return fmt.Errorf("当前异常不允许使用 %s 处理", resolution)
|
||||
}
|
||||
// set 用于本次流程后续判断的set
|
||||
var set string
|
||||
switch resolution {
|
||||
case "continue":
|
||||
set = "status='running',action_cursor=action_cursor+1,action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "retry":
|
||||
set = "status='running',action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "cancel":
|
||||
set = "status='canceled',action_started=0,lease_expires_at=0,next_retry_at=0"
|
||||
default:
|
||||
return errors.New("不支持的人工处理方式")
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET `+set+`,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='needs_review' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, runID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// automationIssuePolicy 封装自动化问题Policy业务协调。
|
||||
func automationIssuePolicy(rawEventJSON string, actionStarted, ruleEnabled bool, sentCount int, errorMessage string) (string, []string) {
|
||||
if actionStarted {
|
||||
// 外部接口没有可依赖的幂等键。结果未知时重放当前游标可能重复发卡、
|
||||
// 发消息或确认发货,因此后端也必须拒绝 retry,不能只依赖前端警告。
|
||||
return "external_result_unknown", []string{"continue", "cancel"}
|
||||
}
|
||||
// raw 用于本次流程后续判断的原始
|
||||
var raw map[string]any
|
||||
if json.Unmarshal([]byte(rawEventJSON), &raw) != nil {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
// accountID 用于本次流程后续判断的账号ID
|
||||
accountID, _ := raw["AccountID"].(string)
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
accountID, _ = raw["account_id"].(string)
|
||||
}
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
if strings.Contains(errorMessage, "规则不存在或已停用") {
|
||||
if ruleEnabled {
|
||||
return "rule_unavailable", []string{"retry", "cancel"}
|
||||
}
|
||||
return "rule_unavailable", []string{"cancel"}
|
||||
}
|
||||
if sentCount > 0 {
|
||||
return "partial_failure", []string{"continue", "retry", "cancel"}
|
||||
}
|
||||
return "execution_failed", []string{"retry", "cancel"}
|
||||
}
|
||||
|
||||
// containsString 封装containsString业务协调。
|
||||
func containsString(values []string, target string) bool {
|
||||
// value 表示当前遍历过程中的值
|
||||
for _, value := range values {
|
||||
if value == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ResolveDeferredIssue 处理Deferred问题。
|
||||
func (a *AutomationRules) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error {
|
||||
if retry {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='pending',attempt_count=0,due_at=0,lease_expires_at=0,error_message='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimDueDeferredTasks 封装ClaimDueDeferred任务列表业务协调。
|
||||
func (a *AutomationRules) ClaimDueDeferredTasks(ctx context.Context, limit int) ([]DeferredAutomationTask, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Unix()
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := a.DB.QueryContext(ctx, `SELECT id,task_key,cookie_id,trigger_type,task_json,due_at,attempt_count
|
||||
FROM automation_pending_tasks
|
||||
WHERE ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?)) AND attempt_count<5
|
||||
ORDER BY due_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// candidates 用于本次流程后续判断的candidates
|
||||
candidates := []DeferredAutomationTask{}
|
||||
for rows.Next() {
|
||||
// task 用于本次流程后续判断的任务
|
||||
var task DeferredAutomationTask
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&task.ID, &task.TaskKey, &task.CookieID, &task.TriggerType, &task.TaskJSON, &task.DueAt, &task.ClaimVersion); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
candidates = append(candidates, task)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// claimed 用于本次流程后续判断的claimed
|
||||
claimed := make([]DeferredAutomationTask, 0, len(candidates))
|
||||
// task 表示当前遍历过程中的任务
|
||||
for _, task := range candidates {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='running',attempt_count=attempt_count+1,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count<5 AND ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?))`, now+300, task.ID, now, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n == 1 {
|
||||
task.ClaimVersion++
|
||||
claimed = append(claimed, task)
|
||||
}
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
// FinishDeferredTask 封装FinishDeferred任务业务协调。
|
||||
func (a *AutomationRules) FinishDeferredTask(ctx context.Context, id int64, claimVersion int, success bool, errMsg string) error {
|
||||
if success {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
// retryDelay 用于本次流程后续判断的重试延迟
|
||||
retryDelay := deferredRetryDelay(claimVersion)
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status=CASE WHEN attempt_count>=5 THEN 'dead_letter' ELSE 'pending' END,
|
||||
due_at=?,lease_expires_at=0,error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(retryDelay).Unix(), errMsg, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
// deferredRetryDelay 封装deferred重试延迟业务协调。
|
||||
func deferredRetryDelay(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
// delay 用于本次流程后续判断的延迟
|
||||
delay := 5 * time.Minute * time.Duration(1<<(attempt-1))
|
||||
if delay > time.Hour {
|
||||
return time.Hour
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// WakeCredentialBlocked 让 Cookie 恢复后的账号尽快重新领取明确尚未发送的任务。
|
||||
func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID string) error {
|
||||
if strings.TrimSpace(cookieID) == "" {
|
||||
return nil
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET due_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='pending'
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='failed' AND action_started=0
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
// RenewDeferredTaskLease 封装RenewDeferred任务Lease业务协调。
|
||||
func (a *AutomationRules) RenewDeferredTaskLease(ctx context.Context, id int64, claimVersion int, leaseExpiresAt int64) error {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, leaseExpiresAt, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
// requireDeferredTaskOwner 封装requireDeferred任务所有者业务协调。
|
||||
func requireDeferredTaskOwner(res sql.Result, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrDeferredTaskLeaseLost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkOrderEventTime 更新订单事件时间字段。字段名由调用方控制白名单。
|
||||
func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field string) error {
|
||||
switch field {
|
||||
case "paid_at", "shipped_at", "completed_at", "buyer_reviewed_at", "last_review_request_at":
|
||||
default:
|
||||
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
|
||||
}
|
||||
// 事件时间列是跨方言 TEXT。不能直接写 CURRENT_TIMESTAMP:Postgres 会产生
|
||||
// "2006-01-02 15:04:05.999999+00",而 MySQL 的无时区文本又取决于会话时区,
|
||||
// 调度器无法可靠解释。统一由应用写 RFC3339 UTC,已有值仍保留(幂等)。
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=?, updated_at=CURRENT_TIMESTAMP WHERE order_id=? AND COALESCE("+field+",'')=''", now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
// IncrementReviewRequest 记录一次求评价请求。
|
||||
func (a *AutomationRules) IncrementReviewRequest(ctx context.Context, orderID string) error {
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `
|
||||
UPDATE orders
|
||||
SET review_request_count=review_request_count+1,
|
||||
last_review_request_at=?,
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE order_id=?`, now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
// DueReviewRequestOrders 返回到期但尚未评价的订单。调度器会再按规则配置做精确判断。
|
||||
func (a *AutomationRules) DueReviewRequestOrders(ctx context.Context, limit int) ([]Order, error) {
|
||||
return a.DueReviewRequestOrdersAfter(ctx, "", limit)
|
||||
}
|
||||
|
||||
// DueReviewRequestOrdersAfter 用不可变的订单 ID 作为稳定游标分页扫描,避免固定 LIMIT
|
||||
// 让旧订单饿死后续订单。不能使用 updated_at:执行求评价动作本身会修改该字段。
|
||||
// DueReviewRequestOrdersAfter 封装DueReview请求订单列表After业务协调。
|
||||
func (a *AutomationRules) DueReviewRequestOrdersAfter(ctx context.Context, afterOrderID string, limit int) ([]Order, error) {
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
// cursorSQL 用于本次流程后续判断的游标SQL
|
||||
cursorSQL := ""
|
||||
// args 用于本次流程后续判断的args
|
||||
args := []any{}
|
||||
if afterOrderID != "" {
|
||||
cursorSQL = " AND o.order_id>?"
|
||||
args = append(args, afterOrderID)
|
||||
}
|
||||
args = append(args, limit)
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_status,cookie_id,is_bargain,
|
||||
receiver_name,receiver_phone,receiver_address,receiver_city,version,chat_id,system_shipped,
|
||||
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
|
||||
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
|
||||
created_at,updated_at
|
||||
FROM orders o
|
||||
WHERE o.system_shipped=1
|
||||
AND o.deleted_at IS NULL
|
||||
AND COALESCE(o.buyer_reviewed_at,'')=''
|
||||
AND COALESCE(o.chat_id,'')<>''
|
||||
AND EXISTS (SELECT 1 FROM automation_rules r
|
||||
WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout'
|
||||
AND r.deleted_at IS NULL AND r.enabled=1
|
||||
AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
|
||||
ORDER BY o.order_id ASC
|
||||
LIMIT ?`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 用于本次流程后续判断的out
|
||||
out := []Order{}
|
||||
for rows.Next() {
|
||||
// ord 用于本次流程后续判断的ord
|
||||
var ord Order
|
||||
// isBargain、version、sysShipped 用于本次流程后续判断的isBargain、version、sysShipped
|
||||
var isBargain, version, sysShipped int
|
||||
// orders 表的可空 TEXT 列必须用 NullString 扫描,旧库数据可能为 NULL
|
||||
// (spec_name/spec_value 等在 init schema 中无 NOT NULL 约束)。
|
||||
// itemID、buyerID、specName、specValue、qty、amount、status、cookieID、receiverName、receiverPhone、receiverAddr、receiverCity、chatID 保存商品ID、buyerID、specName、specValue、qty、amount、status、cookieID、receiverName、receiverPhone、receiverAddr、receiverCity、chatID,供当前处理流程使用
|
||||
var itemID, buyerID, specName, specValue, qty, amount, status, cookieID,
|
||||
receiverName, receiverPhone, receiverAddr, receiverCity, chatID sql.NullString
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&ord.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount,
|
||||
&status, &cookieID, &isBargain, &receiverName, &receiverPhone, &receiverAddr,
|
||||
&receiverCity, &version, &chatID, &sysShipped, &ord.PaidAt,
|
||||
&ord.ShippedAt, &ord.CompletedAt, &ord.BuyerReviewedAt, &ord.LastReviewRequestAt,
|
||||
&ord.ReviewRequestCount, &ord.CreatedAt, &ord.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ord.ItemID = itemID.String
|
||||
ord.BuyerID = buyerID.String
|
||||
ord.SpecName = specName.String
|
||||
ord.SpecValue = specValue.String
|
||||
ord.Quantity = qty.String
|
||||
ord.Amount = amount.String
|
||||
ord.OrderStatus = status.String
|
||||
ord.CookieID = cookieID.String
|
||||
ord.ReceiverName = receiverName.String
|
||||
ord.ReceiverPhone = receiverPhone.String
|
||||
ord.ReceiverAddr = receiverAddr.String
|
||||
ord.ReceiverCity = receiverCity.String
|
||||
ord.ChatID = chatID.String
|
||||
ord.IsBargain = isBargain
|
||||
ord.Version = version
|
||||
ord.SystemShipped = sysShipped != 0
|
||||
out = append(out, ord)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// createAutomationRuleTx 封装create自动化规则Tx业务协调。
|
||||
func createAutomationRuleTx(ctx context.Context, tx *sql.Tx, dialect Dialect, in AutomationRuleInput) (int64, error) {
|
||||
if in.Priority <= 0 {
|
||||
in.Priority = 100
|
||||
}
|
||||
// id、err 用于本次流程后续判断的id、err
|
||||
id, err := insertReturningID(ctx, tx, dialect, `
|
||||
INSERT INTO automation_rules (user_id,cookie_id,item_id,name,trigger_type,enabled,priority,config_json)
|
||||
VALUES (?,?,?,?,?,?,?,?)`,
|
||||
in.UserID, in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// act 表示当前遍历过程中的act
|
||||
for _, act := range in.Actions {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := insertAutomationActionTx(ctx, tx, id, act); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// insertAutomationActionTx 封装insert自动化动作Tx业务协调。
|
||||
func insertAutomationActionTx(ctx context.Context, tx *sql.Tx, ruleID int64, act AutomationActionInput) error {
|
||||
if act.DeliveryCount <= 0 {
|
||||
act.DeliveryCount = 1
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO automation_rule_actions
|
||||
(rule_id,action_type,card_id,delivery_count,message_template,delay_seconds,config_json,enabled,sort_order)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)`,
|
||||
ruleID, act.ActionType, nullInt64(act.CardID), act.DeliveryCount, act.MessageTemplate,
|
||||
act.DelaySeconds, validJSON(act.ConfigJSON), boolToInt(act.Enabled), act.SortOrder)
|
||||
return err
|
||||
}
|
||||
|
||||
// nullInt64 封装nullInt64业务协调。
|
||||
func nullInt64(v int64) any {
|
||||
if v <= 0 {
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// validJSON 封装有效JSON业务协调。
|
||||
func validJSON(s string) string {
|
||||
if s == "" {
|
||||
return "{}"
|
||||
}
|
||||
// v 用于本次流程后续判断的v
|
||||
var v any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(s), &v); err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecoverDefinitelyUnsentReviewRuns 将已证明未发送的评价任务恢复为可重试状态,并返回恢复数量。
|
||||
func (a *AutomationRules) RecoverDefinitelyUnsentReviewRuns(ctx context.Context) (int64, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='failed',action_started=0,lease_expires_at=0,next_retry_at=0,
|
||||
error_message='历史版本在 WebSocket 就绪前执行,已恢复等待安全重试',
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE trigger_type='review_missing_timeout' AND status='needs_review' AND sent_count=0
|
||||
AND (error_message LIKE '%当前没有可用 WebSocket 连接%'
|
||||
OR error_message LIKE '%账号未在线,无法发送自动化消息%'
|
||||
OR error_message LIKE '%账号发送器未初始化%')`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// DeferTask 封装Defer任务业务协调。
|
||||
func (a *AutomationRules) DeferTask(ctx context.Context, task DeferredAutomationTask) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `INSERT INTO automation_pending_tasks
|
||||
(task_key,cookie_id,trigger_type,task_json,due_at,status,attempt_count,lease_expires_at,error_message)
|
||||
VALUES (?,?,?,?,?,'pending',0,0,?)`+dialectUpsert(a.Dialect, []string{"task_key"}, map[string]string{
|
||||
"cookie_id": "excluded.cookie_id",
|
||||
"trigger_type": "excluded.trigger_type",
|
||||
"task_json": "excluded.task_json",
|
||||
"due_at": "excluded.due_at",
|
||||
"status": "'pending'",
|
||||
"attempt_count": "0",
|
||||
"lease_expires_at": "0",
|
||||
"error_message": "excluded.error_message",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt, task.ErrorMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListIssues 读取问题列表。
|
||||
func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]AutomationRunIssue, []DeferredAutomationIssue, error) {
|
||||
// runRows、err 用于本次流程后续判断的运行Rows、err
|
||||
runRows, err := a.DB.QueryContext(ctx, `SELECT ar.id,ar.cookie_id,ar.order_id,ar.trigger_type,ar.error_message,
|
||||
ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0)
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE c.user_id=? AND ar.status='needs_review' AND r.deleted_at IS NULL ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// runs 用于本次流程后续判断的运行记录
|
||||
runs := []AutomationRunIssue{}
|
||||
for runRows.Next() {
|
||||
// issue 用于本次流程后续判断的问题
|
||||
var issue AutomationRunIssue
|
||||
// rawEventJSON 用于本次流程后续判断的原始EventJSON
|
||||
var rawEventJSON string
|
||||
// actionStarted、ruleEnabled 用于本次流程后续判断的动作Started、rule启用状态
|
||||
var actionStarted, ruleEnabled int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := runRows.Scan(&issue.ID, &issue.CookieID, &issue.OrderID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.ActionCursor, &issue.SentCount, &issue.UpdatedAt, &rawEventJSON, &actionStarted, &ruleEnabled); err != nil {
|
||||
_ = runRows.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
issue.IssueKind, issue.AllowedResolutions = automationIssuePolicy(
|
||||
rawEventJSON, actionStarted != 0, ruleEnabled != 0, issue.SentCount, issue.ErrorMessage,
|
||||
)
|
||||
runs = append(runs, issue)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := runRows.Close(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// taskRows、err 用于本次流程后续判断的任务Rows、err
|
||||
taskRows, err := a.DB.QueryContext(ctx, `SELECT apt.id,apt.cookie_id,apt.trigger_type,apt.error_message,
|
||||
apt.attempt_count,apt.updated_at
|
||||
FROM automation_pending_tasks apt JOIN cookies c ON c.id=apt.cookie_id
|
||||
WHERE c.user_id=? AND apt.status='dead_letter' ORDER BY apt.updated_at DESC,apt.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer taskRows.Close()
|
||||
// tasks 用于本次流程后续判断的任务列表
|
||||
tasks := []DeferredAutomationIssue{}
|
||||
for taskRows.Next() {
|
||||
// issue 用于本次流程后续判断的问题
|
||||
var issue DeferredAutomationIssue
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := taskRows.Scan(&issue.ID, &issue.CookieID, &issue.TriggerType, &issue.ErrorMessage,
|
||||
&issue.AttemptCount, &issue.UpdatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tasks = append(tasks, issue)
|
||||
}
|
||||
return runs, tasks, taskRows.Err()
|
||||
}
|
||||
|
||||
// ResolveRunIssue 处理运行问题。
|
||||
func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error {
|
||||
// rawEventJSON、errorMessage 用于本次流程后续判断的原始EventJSON、error消息
|
||||
var rawEventJSON, errorMessage string
|
||||
// actionStarted、ruleEnabled、sentCount 用于本次流程后续判断的动作Started、ruleEnabled、sent数量
|
||||
var actionStarted, ruleEnabled, sentCount int
|
||||
// err 用于本次流程后续判断的err
|
||||
err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message
|
||||
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
|
||||
LEFT JOIN automation_rules r ON r.id=ar.rule_id
|
||||
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=? AND r.deleted_at IS NULL`, runID, userID).
|
||||
Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// allowed 用于本次流程后续判断的allowed
|
||||
_, allowed := automationIssuePolicy(rawEventJSON, actionStarted != 0, ruleEnabled != 0, sentCount, errorMessage)
|
||||
if !containsString(allowed, resolution) {
|
||||
return fmt.Errorf("当前异常不允许使用 %s 处理", resolution)
|
||||
}
|
||||
// set 用于本次流程后续判断的set
|
||||
var set string
|
||||
switch resolution {
|
||||
case "continue":
|
||||
set = "status='running',action_cursor=action_cursor+1,action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "retry":
|
||||
set = "status='running',action_started=0,lease_expires_at=0,next_retry_at=0,error_message=''"
|
||||
case "cancel":
|
||||
set = "status='canceled',action_started=0,lease_expires_at=0,next_retry_at=0"
|
||||
default:
|
||||
return errors.New("不支持的人工处理方式")
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs SET `+set+`,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='needs_review' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, runID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// automationIssuePolicy 封装自动化问题Policy业务协调。
|
||||
func automationIssuePolicy(rawEventJSON string, actionStarted, ruleEnabled bool, sentCount int, errorMessage string) (string, []string) {
|
||||
if actionStarted {
|
||||
// 外部接口没有可依赖的幂等键。结果未知时重放当前游标可能重复发卡、
|
||||
// 发消息或确认发货,因此后端也必须拒绝 retry,不能只依赖前端警告。
|
||||
return "external_result_unknown", []string{"continue", "cancel"}
|
||||
}
|
||||
// raw 用于本次流程后续判断的原始
|
||||
var raw map[string]any
|
||||
if json.Unmarshal([]byte(rawEventJSON), &raw) != nil {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
// accountID 用于本次流程后续判断的账号ID
|
||||
accountID, _ := raw["AccountID"].(string)
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
accountID, _ = raw["account_id"].(string)
|
||||
}
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return "invalid_snapshot", []string{"cancel"}
|
||||
}
|
||||
if strings.Contains(errorMessage, "规则不存在或已停用") {
|
||||
if ruleEnabled {
|
||||
return "rule_unavailable", []string{"retry", "cancel"}
|
||||
}
|
||||
return "rule_unavailable", []string{"cancel"}
|
||||
}
|
||||
if sentCount > 0 {
|
||||
return "partial_failure", []string{"continue", "retry", "cancel"}
|
||||
}
|
||||
return "execution_failed", []string{"retry", "cancel"}
|
||||
}
|
||||
|
||||
// containsString 封装containsString业务协调。
|
||||
func containsString(values []string, target string) bool {
|
||||
// value 表示当前遍历过程中的值
|
||||
for _, value := range values {
|
||||
if value == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ResolveDeferredIssue 处理Deferred问题。
|
||||
func (a *AutomationRules) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error {
|
||||
if retry {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='pending',attempt_count=0,due_at=0,lease_expires_at=0,error_message='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='dead_letter' AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, taskID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimDueDeferredTasks 封装ClaimDueDeferred任务列表业务协调。
|
||||
func (a *AutomationRules) ClaimDueDeferredTasks(ctx context.Context, limit int) ([]DeferredAutomationTask, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Unix()
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := a.DB.QueryContext(ctx, `SELECT id,task_key,cookie_id,trigger_type,task_json,due_at,attempt_count
|
||||
FROM automation_pending_tasks
|
||||
WHERE ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?)) AND attempt_count<5
|
||||
ORDER BY due_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// candidates 用于本次流程后续判断的candidates
|
||||
candidates := []DeferredAutomationTask{}
|
||||
for rows.Next() {
|
||||
// task 用于本次流程后续判断的任务
|
||||
var task DeferredAutomationTask
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&task.ID, &task.TaskKey, &task.CookieID, &task.TriggerType, &task.TaskJSON, &task.DueAt, &task.ClaimVersion); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
candidates = append(candidates, task)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// claimed 用于本次流程后续判断的claimed
|
||||
claimed := make([]DeferredAutomationTask, 0, len(candidates))
|
||||
// task 表示当前遍历过程中的任务
|
||||
for _, task := range candidates {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status='running',attempt_count=attempt_count+1,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count<5 AND ((status='pending' AND due_at<=?) OR (status='running' AND lease_expires_at<?))`, now+300, task.ID, now, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n == 1 {
|
||||
task.ClaimVersion++
|
||||
claimed = append(claimed, task)
|
||||
}
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
// FinishDeferredTask 封装FinishDeferred任务业务协调。
|
||||
func (a *AutomationRules) FinishDeferredTask(ctx context.Context, id int64, claimVersion int, success bool, errMsg string) error {
|
||||
if success {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_pending_tasks
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
// retryDelay 用于本次流程后续判断的重试延迟
|
||||
retryDelay := deferredRetryDelay(claimVersion)
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status=CASE WHEN attempt_count>=5 THEN 'dead_letter' ELSE 'pending' END,
|
||||
due_at=?,lease_expires_at=0,error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(retryDelay).Unix(), errMsg, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
// deferredRetryDelay 封装deferred重试延迟业务协调。
|
||||
func deferredRetryDelay(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
// delay 用于本次流程后续判断的延迟
|
||||
delay := 5 * time.Minute * time.Duration(1<<(attempt-1))
|
||||
if delay > time.Hour {
|
||||
return time.Hour
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// WakeCredentialBlocked 让 Cookie 恢复后的账号尽快重新领取明确尚未发送的任务。
|
||||
func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID string) error {
|
||||
if strings.TrimSpace(cookieID) == "" {
|
||||
return nil
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET due_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='pending'
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='failed' AND action_started=0
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
// RenewDeferredTaskLease 封装RenewDeferred任务Lease业务协调。
|
||||
func (a *AutomationRules) RenewDeferredTaskLease(ctx context.Context, id int64, claimVersion int, leaseExpiresAt int64) error {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, leaseExpiresAt, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
// requireDeferredTaskOwner 封装requireDeferred任务所有者业务协调。
|
||||
func requireDeferredTaskOwner(res sql.Result, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrDeferredTaskLeaseLost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkOrderEventTime 更新订单事件时间字段。字段名由调用方控制白名单。
|
||||
func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field string) error {
|
||||
switch field {
|
||||
case "paid_at", "shipped_at", "completed_at", "buyer_reviewed_at", "last_review_request_at":
|
||||
default:
|
||||
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
|
||||
}
|
||||
// 事件时间列是跨方言 TEXT。不能直接写 CURRENT_TIMESTAMP:Postgres 会产生
|
||||
// "2006-01-02 15:04:05.999999+00",而 MySQL 的无时区文本又取决于会话时区,
|
||||
// 调度器无法可靠解释。统一由应用写 RFC3339 UTC,已有值仍保留(幂等)。
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=?, updated_at=CURRENT_TIMESTAMP WHERE order_id=? AND COALESCE("+field+",'')=''", now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
// IncrementReviewRequest 记录一次求评价请求。
|
||||
func (a *AutomationRules) IncrementReviewRequest(ctx context.Context, orderID string) error {
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := a.DB.ExecContext(ctx, `
|
||||
UPDATE orders
|
||||
SET review_request_count=review_request_count+1,
|
||||
last_review_request_at=?,
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE order_id=?`, now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
// DueReviewRequestOrders 返回到期但尚未评价的订单。调度器会再按规则配置做精确判断。
|
||||
func (a *AutomationRules) DueReviewRequestOrders(ctx context.Context, limit int) ([]Order, error) {
|
||||
return a.DueReviewRequestOrdersAfter(ctx, "", limit)
|
||||
}
|
||||
|
||||
// DueReviewRequestOrdersAfter 用不可变的订单 ID 作为稳定游标分页扫描,避免固定 LIMIT
|
||||
// 让旧订单饿死后续订单。不能使用 updated_at:执行求评价动作本身会修改该字段。
|
||||
// DueReviewRequestOrdersAfter 封装DueReview请求订单列表After业务协调。
|
||||
func (a *AutomationRules) DueReviewRequestOrdersAfter(ctx context.Context, afterOrderID string, limit int) ([]Order, error) {
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
// cursorSQL 用于本次流程后续判断的游标SQL
|
||||
cursorSQL := ""
|
||||
// args 用于本次流程后续判断的args
|
||||
args := []any{}
|
||||
if afterOrderID != "" {
|
||||
cursorSQL = " AND o.order_id>?"
|
||||
args = append(args, afterOrderID)
|
||||
}
|
||||
args = append(args, limit)
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_status,cookie_id,is_bargain,
|
||||
receiver_name,receiver_phone,receiver_address,receiver_city,version,chat_id,system_shipped,
|
||||
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
|
||||
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
|
||||
created_at,updated_at
|
||||
FROM orders o
|
||||
WHERE o.system_shipped=1
|
||||
AND o.deleted_at IS NULL
|
||||
AND COALESCE(o.buyer_reviewed_at,'')=''
|
||||
AND COALESCE(o.chat_id,'')<>''
|
||||
AND EXISTS (SELECT 1 FROM automation_rules r
|
||||
WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout'
|
||||
AND r.deleted_at IS NULL AND r.enabled=1
|
||||
AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
|
||||
ORDER BY o.order_id ASC
|
||||
LIMIT ?`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 用于本次流程后续判断的out
|
||||
out := []Order{}
|
||||
for rows.Next() {
|
||||
// ord 用于本次流程后续判断的ord
|
||||
var ord Order
|
||||
// isBargain、version、sysShipped 用于本次流程后续判断的isBargain、version、sysShipped
|
||||
var isBargain, version, sysShipped int
|
||||
// orders 表的可空 TEXT 列必须用 NullString 扫描,旧库数据可能为 NULL
|
||||
// (spec_name/spec_value 等在 init schema 中无 NOT NULL 约束)。
|
||||
// itemID、buyerID、specName、specValue、qty、amount、status、cookieID、receiverName、receiverPhone、receiverAddr、receiverCity、chatID 保存商品ID、buyerID、specName、specValue、qty、amount、status、cookieID、receiverName、receiverPhone、receiverAddr、receiverCity、chatID,供当前处理流程使用
|
||||
var itemID, buyerID, specName, specValue, qty, amount, status, cookieID,
|
||||
receiverName, receiverPhone, receiverAddr, receiverCity, chatID sql.NullString
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&ord.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount,
|
||||
&status, &cookieID, &isBargain, &receiverName, &receiverPhone, &receiverAddr,
|
||||
&receiverCity, &version, &chatID, &sysShipped, &ord.PaidAt,
|
||||
&ord.ShippedAt, &ord.CompletedAt, &ord.BuyerReviewedAt, &ord.LastReviewRequestAt,
|
||||
&ord.ReviewRequestCount, &ord.CreatedAt, &ord.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ord.ItemID = itemID.String
|
||||
ord.BuyerID = buyerID.String
|
||||
ord.SpecName = specName.String
|
||||
ord.SpecValue = specValue.String
|
||||
ord.Quantity = qty.String
|
||||
ord.Amount = amount.String
|
||||
ord.OrderStatus = status.String
|
||||
ord.CookieID = cookieID.String
|
||||
ord.ReceiverName = receiverName.String
|
||||
ord.ReceiverPhone = receiverPhone.String
|
||||
ord.ReceiverAddr = receiverAddr.String
|
||||
ord.ReceiverCity = receiverCity.String
|
||||
ord.ChatID = chatID.String
|
||||
ord.IsBargain = isBargain
|
||||
ord.Version = version
|
||||
ord.SystemShipped = sysShipped != 0
|
||||
out = append(out, ord)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// createAutomationRuleTx 封装create自动化规则Tx业务协调。
|
||||
func createAutomationRuleTx(ctx context.Context, tx *sql.Tx, dialect Dialect, in AutomationRuleInput) (int64, error) {
|
||||
if in.Priority <= 0 {
|
||||
in.Priority = 100
|
||||
}
|
||||
// id、err 用于本次流程后续判断的id、err
|
||||
id, err := insertReturningID(ctx, tx, dialect, `
|
||||
INSERT INTO automation_rules (user_id,cookie_id,item_id,name,trigger_type,enabled,priority,config_json)
|
||||
VALUES (?,?,?,?,?,?,?,?)`,
|
||||
in.UserID, in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// act 表示当前遍历过程中的act
|
||||
for _, act := range in.Actions {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := insertAutomationActionTx(ctx, tx, id, act); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// insertAutomationActionTx 封装insert自动化动作Tx业务协调。
|
||||
func insertAutomationActionTx(ctx context.Context, tx *sql.Tx, ruleID int64, act AutomationActionInput) error {
|
||||
if act.DeliveryCount <= 0 {
|
||||
act.DeliveryCount = 1
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO automation_rule_actions
|
||||
(rule_id,action_type,card_id,delivery_count,message_template,delay_seconds,config_json,enabled,sort_order)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)`,
|
||||
ruleID, act.ActionType, nullInt64(act.CardID), act.DeliveryCount, act.MessageTemplate,
|
||||
act.DelaySeconds, validJSON(act.ConfigJSON), boolToInt(act.Enabled), act.SortOrder)
|
||||
return err
|
||||
}
|
||||
|
||||
// nullInt64 封装nullInt64业务协调。
|
||||
func nullInt64(v int64) any {
|
||||
if v <= 0 {
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// validJSON 封装有效JSON业务协调。
|
||||
func validJSON(s string) string {
|
||||
if s == "" {
|
||||
return "{}"
|
||||
}
|
||||
// v 用于本次流程后续判断的v
|
||||
var v any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(s), &v); err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -762,276 +762,3 @@ type ItemSyncResult struct {
|
||||
}
|
||||
|
||||
// AllForCookie 取某账号全部商品。
|
||||
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := i.DB.QueryContext(ctx,
|
||||
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
|
||||
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
|
||||
is_multi_spec, COALESCE(multi_quantity_delivery,0)
|
||||
FROM item_info WHERE cookie_id=? AND deleted_at IS NULL ORDER BY id DESC`, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// ListForUser 一次查询用户范围内的全部商品,可选按账号 ID 过滤。
|
||||
func (i *Items) ListForUser(ctx context.Context, userID int64, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 保存用户范围商品查询结果及错误。
|
||||
rows, err := i.DB.QueryContext(ctx,
|
||||
`SELECT i.id, i.cookie_id, i.item_id, COALESCE(i.item_title,''), COALESCE(i.item_description,''),
|
||||
COALESCE(i.item_category,''), COALESCE(i.item_price,''), COALESCE(i.item_detail,''),
|
||||
i.is_multi_spec, COALESCE(i.multi_quantity_delivery,0)
|
||||
FROM item_info i JOIN cookies c ON c.id=i.cookie_id
|
||||
WHERE c.user_id=? AND (?='' OR i.cookie_id=?) AND i.deleted_at IS NULL
|
||||
ORDER BY i.id DESC`, userID, cookieID, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// scanItemInfoRows 将商品查询游标转换为统一的商品行模型。
|
||||
func scanItemInfoRows(rows *sql.Rows) ([]ItemInfoRow, error) {
|
||||
// out 用于本次流程后续判断的out
|
||||
var out []ItemInfoRow
|
||||
for rows.Next() {
|
||||
// r 用于本次流程后续判断的r
|
||||
var r ItemInfoRow
|
||||
// isMulti、multiQty 用于本次流程后续判断的isMulti、multiQty
|
||||
var isMulti, multiQty int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&r.ID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.ItemDescription,
|
||||
&r.ItemCategory, &r.ItemPrice, &r.ItemDetail, &isMulti, &multiQty); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.IsMultiSpec = isMulti != 0
|
||||
r.MultiQuantityDelivery = multiQty != 0
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Upsert 插入或更新商品信息。
|
||||
func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
|
||||
item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(i.Dialect, []string{"cookie_id", "item_id"}, map[string]string{
|
||||
"item_title": "EXCLUDED.item_title",
|
||||
"item_description": "EXCLUDED.item_description",
|
||||
"item_category": "EXCLUDED.item_category",
|
||||
"item_price": "EXCLUDED.item_price",
|
||||
"item_detail": "EXCLUDED.item_detail",
|
||||
"is_multi_spec": "EXCLUDED.is_multi_spec",
|
||||
"multi_quantity_delivery": "EXCLUDED.multi_quantity_delivery",
|
||||
"deleted_at": "NULL",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
|
||||
nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail),
|
||||
boolToInt(r.IsMultiSpec), boolToInt(r.MultiQuantityDelivery))
|
||||
return err
|
||||
}
|
||||
|
||||
// UpsertBasic 插入或补全商品基础信息,不覆盖已有的多规格/多数量发货设置。
|
||||
func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, i.DB, r)
|
||||
}
|
||||
|
||||
// UpsertBasicTx 封装UpsertBasicTx业务协调。
|
||||
func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, tx, r)
|
||||
}
|
||||
|
||||
// SyncFromRemote 将远端商品全集同步到本地。
|
||||
//
|
||||
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
|
||||
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
|
||||
// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。
|
||||
// SyncFromRemote 同步FromRemote。
|
||||
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
|
||||
cookieID = strings.TrimSpace(cookieID)
|
||||
if cookieID == "" {
|
||||
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
|
||||
}
|
||||
|
||||
// remoteIDs 用于本次流程后续判断的remoteIDs
|
||||
remoteIDs := make(map[string]struct{}, len(rows))
|
||||
// validRows 用于本次流程后续判断的有效Rows
|
||||
validRows := make([]ItemInfoRow, 0, len(rows))
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range rows {
|
||||
row.CookieID = cookieID
|
||||
row.ItemID = strings.TrimSpace(row.ItemID)
|
||||
if row.ItemID == "" {
|
||||
continue
|
||||
}
|
||||
if // exists 用于本次流程后续判断的exists
|
||||
_, exists := remoteIDs[row.ItemID]; exists {
|
||||
continue
|
||||
}
|
||||
remoteIDs[row.ItemID] = struct{}{}
|
||||
validRows = append(validRows, row)
|
||||
}
|
||||
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := i.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
// rollback 用于本次流程后续判断的rollback
|
||||
rollback := func(err error) (ItemSyncResult, error) {
|
||||
_ = tx.Rollback()
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
// index 表示当前遍历过程中的index
|
||||
for index := range validRows {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if validRows[index].IsMultiSpec {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
|
||||
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// args 用于本次流程后续判断的args
|
||||
args := make([]any, 0, len(remoteIDs)+1)
|
||||
args = append(args, cookieID)
|
||||
// deleteQuery 用于本次流程后续判断的delete查询
|
||||
deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL`
|
||||
if len(remoteIDs) > 0 {
|
||||
// placeholders 用于本次流程后续判断的placeholders
|
||||
placeholders := make([]string, 0, len(remoteIDs))
|
||||
// itemID 表示当前遍历过程中的商品ID
|
||||
for itemID := range remoteIDs {
|
||||
placeholders = append(placeholders, "?")
|
||||
args = append(args, itemID)
|
||||
}
|
||||
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
|
||||
}
|
||||
// deletedResult、err 用于本次流程后续判断的deletedResult、err
|
||||
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
// deleted、err 用于本次流程后续判断的deleted、err
|
||||
deleted, err := deletedResult.RowsAffected()
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
// ruleArgs 用于本次流程后续判断的规则Args
|
||||
ruleArgs := make([]any, 0, len(remoteIDs)+1)
|
||||
ruleArgs = append(ruleArgs, cookieID)
|
||||
// ruleQuery 用于本次流程后续判断的规则查询
|
||||
ruleQuery := `UPDATE automation_rules
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL`
|
||||
if len(remoteIDs) > 0 {
|
||||
// placeholders 用于本次流程后续判断的placeholders
|
||||
placeholders := make([]string, 0, len(remoteIDs))
|
||||
// itemID 表示当前遍历过程中的商品ID
|
||||
for itemID := range remoteIDs {
|
||||
placeholders = append(placeholders, "?")
|
||||
ruleArgs = append(ruleArgs, itemID)
|
||||
}
|
||||
ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
|
||||
}
|
||||
|
||||
// upsertBasic 封装upsertBasic业务协调。
|
||||
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
|
||||
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
|
||||
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
|
||||
// conflictClause 用于本次流程后续判断的conflictClause
|
||||
var conflictClause string
|
||||
switch i.Dialect {
|
||||
case DialectMySQL:
|
||||
conflictClause = ` ON DUPLICATE KEY UPDATE
|
||||
item_title=CASE WHEN VALUES(item_title) IS NOT NULL AND VALUES(item_title) != '' THEN VALUES(item_title) ELSE item_info.item_title END,
|
||||
item_description=CASE WHEN VALUES(item_description) IS NOT NULL AND VALUES(item_description) != '' THEN VALUES(item_description) ELSE item_info.item_description END,
|
||||
item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END,
|
||||
item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END,
|
||||
item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END,
|
||||
deleted_at=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP`
|
||||
default:
|
||||
conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET
|
||||
item_title=CASE WHEN EXCLUDED.item_title IS NOT NULL AND EXCLUDED.item_title != '' THEN EXCLUDED.item_title ELSE item_info.item_title END,
|
||||
item_description=CASE WHEN EXCLUDED.item_description IS NOT NULL AND EXCLUDED.item_description != '' THEN EXCLUDED.item_description ELSE item_info.item_description END,
|
||||
item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END,
|
||||
item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END,
|
||||
item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END,
|
||||
deleted_at=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP`
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := execer.ExecContext(ctx,
|
||||
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
|
||||
item_category, item_price, item_detail, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+conflictClause,
|
||||
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
|
||||
nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail))
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。
|
||||
func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := i.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE item_info
|
||||
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE automation_rules
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// SetMultiSpec 设置多规格开关。
|
||||
func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
|
||||
boolToInt(on), cookieID, itemID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetMultiQuantity 设置多数量发货开关。
|
||||
func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
|
||||
boolToInt(on), cookieID, itemID)
|
||||
return err
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ItemPublishBatches 管理商品批量发布批次及其明细行的持久化。
|
||||
@@ -544,408 +543,3 @@ func recountBatchTx(ctx context.Context, tx *sql.Tx, batchID string) error {
|
||||
}
|
||||
|
||||
// Delete 删除当前值。
|
||||
func (b *ItemPublishBatches) Delete(ctx context.Context, userID int64, batchID string) error {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `DELETE FROM item_publish_batches WHERE id=? AND user_id=? AND status NOT IN ('running','canceling')`, batchID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExpiredUploads 封装ExpiredUploads业务协调。
|
||||
func (b *ItemPublishBatches) ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]ItemPublishBatch, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
total_count,success_count,failed_count,worker_token,lease_expires_at,created_at,updated_at
|
||||
FROM item_publish_batches
|
||||
WHERE upload_dir<>'' AND status NOT IN ('running','canceling') AND updated_at<?
|
||||
ORDER BY updated_at LIMIT ?`, cutoff, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 用于本次流程后续判断的out
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
// batch 用于本次流程后续判断的批次
|
||||
var batch ItemPublishBatch
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, batch)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ClearUploadDir 封装ClearUploadDir业务协调。
|
||||
func (b *ItemPublishBatches) ClearUploadDir(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches SET upload_dir='',updated_at=CURRENT_TIMESTAMP WHERE id=?`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetInterrupted 只重置确认由进程中断造成的失败行,不自动重试业务失败或远端状态不确定的行。
|
||||
func (b *ItemPublishBatches) ResetInterrupted(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed' AND failure_kind='interrupted'`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimBatch 原子领取一个非运行批次。并发请求中只有一个 worker 能成功。
|
||||
func (b *ItemPublishBatches) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='running',worker_token=?,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND (status IN ('preview','pending','failed','partially_failed','completed','canceled')
|
||||
OR (status='running' AND (lease_expires_at=0 OR lease_expires_at<?)))`,
|
||||
workerToken, leaseExpiresAt, batchID, time.Now().UTC().Unix())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
// 远端发布已经开始但尚未保存商品 ID 的行结果未知,绝不能自动重放。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',worker_token='',error_message='上次任务在远端发布期间中断;结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>? AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 仅把确定尚未进入远端副作用,或已经保存远端商品 ID 的行重新放回队列。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',worker_token='',error_message='上次任务租约已过期,等待重试',failure_kind='interrupted',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>?`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RenewBatchLease 仅允许当前 worker 延长租约,长批次不会因固定截止时间被并发接管。
|
||||
func (b *ItemPublishBatches) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, leaseExpiresAt, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// ReservePublishSlot 仅在当前 worker 仍持有运行中批次且上一时隙已满足间隔时原子记录新的发布开始时刻。
|
||||
func (b *ItemPublishBatches) ReservePublishSlot(ctx context.Context, batchID, workerToken string, minimumLastStartedAtMillis, startedAtMillis int64) (bool, error) {
|
||||
// res、err 保存原子时隙更新结果。
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET last_publish_started_at_millis=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(last_publish_started_at_millis,0)<=?`,
|
||||
startedAtMillis, batchID, workerToken, minimumLastStartedAtMillis)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、rowsErr 保存本次时隙更新影响的行数及读取错误。
|
||||
n, rowsErr := res.RowsAffected()
|
||||
return rowsErr == nil && n == 1, rowsErr
|
||||
}
|
||||
|
||||
// FailClaimedBatch 释放初始化阶段失败的批次租约。worker token 防止旧 worker
|
||||
// 覆盖已经被新 worker 接管的状态。
|
||||
// FailClaimedBatch 封装FailClaimed批次业务协调。
|
||||
func (b *ItemPublishBatches) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='failed',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinishBatchStatus 只允许当前持有租约的 worker 结束批次。
|
||||
func (b *ItemPublishBatches) FinishBatchStatus(ctx context.Context, batchID, workerToken, status string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinalizeBatch 在单个事务内重算计数,并且只在所有行都进入终态后结束批次。
|
||||
func (b *ItemPublishBatches) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// total、success、failed、unfinished 用于本次流程后续判断的total、success、failed、unfinished
|
||||
var total, success, failed, unfinished int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.QueryRowContext(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status NOT IN ('success','failed') THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).
|
||||
Scan(&total, &success, &failed, &unfinished); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if unfinished != 0 || total != success+failed {
|
||||
return "", false, errors.New("批次仍有未完成行,不能进入终态")
|
||||
}
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := finalBatchStatus(success, failed)
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,total_count=?,success_count=?,failed_count=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, total, success, failed, batchID, workerToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return "", false, err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return status, true, nil
|
||||
}
|
||||
|
||||
// BatchStatus 取批次状态。未找到返回 ErrNotFound。
|
||||
func (b *ItemPublishBatches) BatchStatus(ctx context.Context, batchID string) (string, error) {
|
||||
// status 用于本次流程后续判断的状态
|
||||
var status string
|
||||
// err 用于本次流程后续判断的err
|
||||
err := b.DB.QueryRowContext(ctx, `SELECT status FROM item_publish_batches WHERE id=?`, batchID).Scan(&status)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// MarkRowRunning 将明细行置为 running 并清空历史错误信息(发布 worker 开始处理时调用)。
|
||||
func (b *ItemPublishBatches) MarkRowRunning(ctx context.Context, rowID int64) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='running',error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP WHERE id=? AND status='pending'`, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimRow 原子领取单行,防止多个 worker 重复发布同一商品。
|
||||
func (b *ItemPublishBatches) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='running',worker_token=?,error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='pending'
|
||||
AND EXISTS (SELECT 1 FROM item_publish_batches b
|
||||
WHERE b.id=item_publish_batch_rows.batch_id AND b.status='running' AND b.worker_token=?)`,
|
||||
workerToken, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRemoteStarted 在调用闲鱼发布接口前落盘。进程若在远端返回前硬退出,
|
||||
// 租约接管方会把该行隔离为 uncertain_remote,而不是再次发布。
|
||||
// MarkClaimedRemoteStarted 封装MarkClaimedRemoteStarted业务协调。
|
||||
func (b *ItemPublishBatches) MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET failure_kind='remote_started',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(item_id,'')=''`, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowSuccess 只允许领取该行的 worker 写入成功结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// SaveClaimedRemoteResult 在闲鱼发布成功后第一时间保存远端商品标识。
|
||||
// 后续本地商品/自动化规则写入失败时,重试会从该断点继续而不会再次调用发布接口。
|
||||
// SaveClaimedRemoteResult 保存ClaimedRemote结果。
|
||||
func (b *ItemPublishBatches) SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if strings.TrimSpace(itemID) == "" {
|
||||
return false, errors.New("远端发布结果缺少商品ID")
|
||||
}
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET item_id=?,item_url=?,raw_json=?,failure_kind='post_publish',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowFailed 只允许领取该行的 worker 写入失败结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, message, kind, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkRowSuccess 标记明细行发布成功,回填闲鱼商品 ID、URL 与原始返回 JSON。
|
||||
func (b *ItemPublishBatches) MarkRowSuccess(ctx context.Context, rowID int64, itemID, itemURL, rawJSON string) error {
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, itemID, itemURL, rawJSON, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRowFailed 标记明细行发布失败并记录错误原因。
|
||||
func (b *ItemPublishBatches) MarkRowFailed(ctx context.Context, rowID int64, message string) error {
|
||||
return b.MarkRowFailedKind(ctx, rowID, message, "publish")
|
||||
}
|
||||
|
||||
// MarkRowFailedKind 封装MarkRow失败类型业务协调。
|
||||
func (b *ItemPublishBatches) MarkRowFailedKind(ctx context.Context, rowID int64, message, kind string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
message, kind, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRunningFailed 将批次内仍在 running 的行标为失败。
|
||||
func (b *ItemPublishBatches) MarkRunningFailed(ctx context.Context, batchID, message string) error {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running'`,
|
||||
message, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkUnfinishedFailed 将批次内 pending/running 行标为失败。
|
||||
func (b *ItemPublishBatches) MarkUnfinishedFailed(ctx context.Context, batchID, message string) error {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status IN ('pending','running')`,
|
||||
message, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetFailed 将批次内所有 failed 行重置为 pending,便于失败重试。
|
||||
func (b *ItemPublishBatches) ResetFailed(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed'
|
||||
AND COALESCE(failure_kind,'') NOT IN ('validation','uncertain_remote')`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// Recount 按明细行实际状态重算批次的 total/success/failed 计数。
|
||||
// worker 每完成一行后调用,保证前端进度与 DB 一致。
|
||||
// Recount 封装Recount业务协调。
|
||||
func (b *ItemPublishBatches) Recount(ctx context.Context, batchID string) error {
|
||||
// total、success、failed 用于本次流程后续判断的total、success、failed
|
||||
var total, success, failed int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := b.DB.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).Scan(&total, &success, &failed); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batches
|
||||
SET total_count=?,success_count=?,failed_count=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, total, success, failed, batchID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Delete 删除属于指定用户的批量发布任务及其明细;调用方负责先清理对应上传目录。
|
||||
func (b *ItemPublishBatches) Delete(ctx context.Context, userID int64, batchID string) error {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `DELETE FROM item_publish_batches WHERE id=? AND user_id=? AND status NOT IN ('running','canceling')`, batchID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // n 用于本次流程后续判断的n
|
||||
n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExpiredUploads 封装ExpiredUploads业务协调。
|
||||
func (b *ItemPublishBatches) ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]ItemPublishBatch, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,
|
||||
total_count,success_count,failed_count,worker_token,lease_expires_at,created_at,updated_at
|
||||
FROM item_publish_batches
|
||||
WHERE upload_dir<>'' AND status NOT IN ('running','canceling') AND updated_at<?
|
||||
ORDER BY updated_at LIMIT ?`, cutoff, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 用于本次流程后续判断的out
|
||||
var out []ItemPublishBatch
|
||||
for rows.Next() {
|
||||
// batch 用于本次流程后续判断的批次
|
||||
var batch ItemPublishBatch
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, batch)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ClearUploadDir 封装ClearUploadDir业务协调。
|
||||
func (b *ItemPublishBatches) ClearUploadDir(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches SET upload_dir='',updated_at=CURRENT_TIMESTAMP WHERE id=?`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetInterrupted 只重置确认由进程中断造成的失败行,不自动重试业务失败或远端状态不确定的行。
|
||||
func (b *ItemPublishBatches) ResetInterrupted(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed' AND failure_kind='interrupted'`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimBatch 原子领取一个非运行批次。并发请求中只有一个 worker 能成功。
|
||||
func (b *ItemPublishBatches) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='running',worker_token=?,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND (status IN ('preview','pending','failed','partially_failed','completed','canceled')
|
||||
OR (status='running' AND (lease_expires_at=0 OR lease_expires_at<?)))`,
|
||||
workerToken, leaseExpiresAt, batchID, time.Now().UTC().Unix())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return false, err
|
||||
}
|
||||
// 远端发布已经开始但尚未保存商品 ID 的行结果未知,绝不能自动重放。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',worker_token='',error_message='上次任务在远端发布期间中断;结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>? AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 仅把确定尚未进入远端副作用,或已经保存远端商品 ID 的行重新放回队列。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='pending',worker_token='',error_message='上次任务租约已过期,等待重试',failure_kind='interrupted',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND worker_token<>?`, batchID, workerToken); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RenewBatchLease 仅允许当前 worker 延长租约,长批次不会因固定截止时间被并发接管。
|
||||
func (b *ItemPublishBatches) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, leaseExpiresAt, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// ReservePublishSlot 仅在当前 worker 仍持有运行中批次且上一时隙已满足间隔时原子记录新的发布开始时刻。
|
||||
func (b *ItemPublishBatches) ReservePublishSlot(ctx context.Context, batchID, workerToken string, minimumLastStartedAtMillis, startedAtMillis int64) (bool, error) {
|
||||
// res、err 保存原子时隙更新结果。
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET last_publish_started_at_millis=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(last_publish_started_at_millis,0)<=?`,
|
||||
startedAtMillis, batchID, workerToken, minimumLastStartedAtMillis)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、rowsErr 保存本次时隙更新影响的行数及读取错误。
|
||||
n, rowsErr := res.RowsAffected()
|
||||
return rowsErr == nil && n == 1, rowsErr
|
||||
}
|
||||
|
||||
// FailClaimedBatch 释放初始化阶段失败的批次租约。worker token 防止旧 worker
|
||||
// 覆盖已经被新 worker 接管的状态。
|
||||
// FailClaimedBatch 封装FailClaimed批次业务协调。
|
||||
func (b *ItemPublishBatches) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status='failed',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinishBatchStatus 只允许当前持有租约的 worker 结束批次。
|
||||
func (b *ItemPublishBatches) FinishBatchStatus(ctx context.Context, batchID, workerToken, status string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, batchID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// FinalizeBatch 在单个事务内重算计数,并且只在所有行都进入终态后结束批次。
|
||||
func (b *ItemPublishBatches) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// total、success、failed、unfinished 用于本次流程后续判断的total、success、failed、unfinished
|
||||
var total, success, failed, unfinished int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.QueryRowContext(ctx, `SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status NOT IN ('success','failed') THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).
|
||||
Scan(&total, &success, &failed, &unfinished); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if unfinished != 0 || total != success+failed {
|
||||
return "", false, errors.New("批次仍有未完成行,不能进入终态")
|
||||
}
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := finalBatchStatus(success, failed)
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := tx.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET status=?,total_count=?,success_count=?,failed_count=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, status, total, success, failed, batchID, workerToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil || n != 1 {
|
||||
return "", false, err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return status, true, nil
|
||||
}
|
||||
|
||||
// BatchStatus 取批次状态。未找到返回 ErrNotFound。
|
||||
func (b *ItemPublishBatches) BatchStatus(ctx context.Context, batchID string) (string, error) {
|
||||
// status 用于本次流程后续判断的状态
|
||||
var status string
|
||||
// err 用于本次流程后续判断的err
|
||||
err := b.DB.QueryRowContext(ctx, `SELECT status FROM item_publish_batches WHERE id=?`, batchID).Scan(&status)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// MarkRowRunning 将明细行置为 running 并清空历史错误信息(发布 worker 开始处理时调用)。
|
||||
func (b *ItemPublishBatches) MarkRowRunning(ctx context.Context, rowID int64) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='running',error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP WHERE id=? AND status='pending'`, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClaimRow 原子领取单行,防止多个 worker 重复发布同一商品。
|
||||
func (b *ItemPublishBatches) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='running',worker_token=?,error_message='',failure_kind='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='pending'
|
||||
AND EXISTS (SELECT 1 FROM item_publish_batches b
|
||||
WHERE b.id=item_publish_batch_rows.batch_id AND b.status='running' AND b.worker_token=?)`,
|
||||
workerToken, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRemoteStarted 在调用闲鱼发布接口前落盘。进程若在远端返回前硬退出,
|
||||
// 租约接管方会把该行隔离为 uncertain_remote,而不是再次发布。
|
||||
// MarkClaimedRemoteStarted 封装MarkClaimedRemoteStarted业务协调。
|
||||
func (b *ItemPublishBatches) MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET failure_kind='remote_started',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(item_id,'')=''`, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowSuccess 只允许领取该行的 worker 写入成功结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// SaveClaimedRemoteResult 在闲鱼发布成功后第一时间保存远端商品标识。
|
||||
// 后续本地商品/自动化规则写入失败时,重试会从该断点继续而不会再次调用发布接口。
|
||||
// SaveClaimedRemoteResult 保存ClaimedRemote结果。
|
||||
func (b *ItemPublishBatches) SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
|
||||
if strings.TrimSpace(itemID) == "" {
|
||||
return false, errors.New("远端发布结果缺少商品ID")
|
||||
}
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET item_id=?,item_url=?,raw_json=?,failure_kind='post_publish',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, itemID, itemURL, rawJSON, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkClaimedRowFailed 只允许领取该行的 worker 写入失败结果。
|
||||
func (b *ItemPublishBatches) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, message, kind, rowID, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := res.RowsAffected()
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// MarkRowSuccess 标记明细行发布成功,回填闲鱼商品 ID、URL 与原始返回 JSON。
|
||||
func (b *ItemPublishBatches) MarkRowSuccess(ctx context.Context, rowID int64, itemID, itemURL, rawJSON string) error {
|
||||
if rawJSON == "" {
|
||||
rawJSON = "{}"
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='success',item_id=?,item_url=?,error_message='',failure_kind='',worker_token='',raw_json=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, itemID, itemURL, rawJSON, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRowFailed 标记明细行发布失败并记录错误原因。
|
||||
func (b *ItemPublishBatches) MarkRowFailed(ctx context.Context, rowID int64, message string) error {
|
||||
return b.MarkRowFailedKind(ctx, rowID, message, "publish")
|
||||
}
|
||||
|
||||
// MarkRowFailedKind 封装MarkRow失败类型业务协调。
|
||||
func (b *ItemPublishBatches) MarkRowFailedKind(ctx context.Context, rowID int64, message, kind string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows SET status='failed',error_message=?,failure_kind=?,worker_token='',updated_at=CURRENT_TIMESTAMP WHERE id=?`,
|
||||
message, kind, rowID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkRunningFailed 将批次内仍在 running 的行标为失败。
|
||||
func (b *ItemPublishBatches) MarkRunningFailed(ctx context.Context, batchID, message string) error {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running'`,
|
||||
message, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkUnfinishedFailed 将批次内 pending/running 行标为失败。
|
||||
func (b *ItemPublishBatches) MarkUnfinishedFailed(ctx context.Context, batchID, message string) error {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message='远端发布结果未知,请人工核对闲鱼商品列表',failure_kind='uncertain_remote',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='running' AND failure_kind='remote_started' AND COALESCE(item_id,'')=''`, batchID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='failed',error_message=?,failure_kind='interrupted',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status IN ('pending','running')`,
|
||||
message, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResetFailed 将批次内所有 failed 行重置为 pending,便于失败重试。
|
||||
func (b *ItemPublishBatches) ResetFailed(ctx context.Context, batchID string) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batch_rows
|
||||
SET status='pending',error_message='',failure_kind='',worker_token='',updated_at=CURRENT_TIMESTAMP
|
||||
WHERE batch_id=? AND status='failed'
|
||||
AND COALESCE(failure_kind,'') NOT IN ('validation','uncertain_remote')`, batchID)
|
||||
return err
|
||||
}
|
||||
|
||||
// Recount 按明细行实际状态重算批次的 total/success/failed 计数。
|
||||
// worker 每完成一行后调用,保证前端进度与 DB 一致。
|
||||
// Recount 封装Recount业务协调。
|
||||
func (b *ItemPublishBatches) Recount(ctx context.Context, batchID string) error {
|
||||
// total、success、failed 用于本次流程后续判断的total、success、failed
|
||||
var total, success, failed int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := b.DB.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0)
|
||||
FROM item_publish_batch_rows WHERE batch_id=?`, batchID).Scan(&total, &success, &failed); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := b.DB.ExecContext(ctx,
|
||||
`UPDATE item_publish_batches
|
||||
SET total_count=?,success_count=?,failed_count=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`, total, success, failed, batchID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AllForCookie 返回一个账号下的全部商品持久化记录,不包含账号凭证明文。
|
||||
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := i.DB.QueryContext(ctx,
|
||||
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
|
||||
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
|
||||
is_multi_spec, COALESCE(multi_quantity_delivery,0)
|
||||
FROM item_info WHERE cookie_id=? AND deleted_at IS NULL ORDER BY id DESC`, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// ListForUser 一次查询用户范围内的全部商品,可选按账号 ID 过滤。
|
||||
func (i *Items) ListForUser(ctx context.Context, userID int64, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 保存用户范围商品查询结果及错误。
|
||||
rows, err := i.DB.QueryContext(ctx,
|
||||
`SELECT i.id, i.cookie_id, i.item_id, COALESCE(i.item_title,''), COALESCE(i.item_description,''),
|
||||
COALESCE(i.item_category,''), COALESCE(i.item_price,''), COALESCE(i.item_detail,''),
|
||||
i.is_multi_spec, COALESCE(i.multi_quantity_delivery,0)
|
||||
FROM item_info i JOIN cookies c ON c.id=i.cookie_id
|
||||
WHERE c.user_id=? AND (?='' OR i.cookie_id=?) AND i.deleted_at IS NULL
|
||||
ORDER BY i.id DESC`, userID, cookieID, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// scanItemInfoRows 将商品查询游标转换为统一的商品行模型。
|
||||
func scanItemInfoRows(rows *sql.Rows) ([]ItemInfoRow, error) {
|
||||
// out 用于本次流程后续判断的out
|
||||
var out []ItemInfoRow
|
||||
for rows.Next() {
|
||||
// r 用于本次流程后续判断的r
|
||||
var r ItemInfoRow
|
||||
// isMulti、multiQty 用于本次流程后续判断的isMulti、multiQty
|
||||
var isMulti, multiQty int
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&r.ID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.ItemDescription,
|
||||
&r.ItemCategory, &r.ItemPrice, &r.ItemDetail, &isMulti, &multiQty); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.IsMultiSpec = isMulti != 0
|
||||
r.MultiQuantityDelivery = multiQty != 0
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Upsert 插入或更新商品信息。
|
||||
func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
|
||||
item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(i.Dialect, []string{"cookie_id", "item_id"}, map[string]string{
|
||||
"item_title": "EXCLUDED.item_title",
|
||||
"item_description": "EXCLUDED.item_description",
|
||||
"item_category": "EXCLUDED.item_category",
|
||||
"item_price": "EXCLUDED.item_price",
|
||||
"item_detail": "EXCLUDED.item_detail",
|
||||
"is_multi_spec": "EXCLUDED.is_multi_spec",
|
||||
"multi_quantity_delivery": "EXCLUDED.multi_quantity_delivery",
|
||||
"deleted_at": "NULL",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
|
||||
nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail),
|
||||
boolToInt(r.IsMultiSpec), boolToInt(r.MultiQuantityDelivery))
|
||||
return err
|
||||
}
|
||||
|
||||
// UpsertBasic 插入或补全商品基础信息,不覆盖已有的多规格/多数量发货设置。
|
||||
func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, i.DB, r)
|
||||
}
|
||||
|
||||
// UpsertBasicTx 封装UpsertBasicTx业务协调。
|
||||
func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) error {
|
||||
return i.upsertBasic(ctx, tx, r)
|
||||
}
|
||||
|
||||
// SyncFromRemote 将远端商品全集同步到本地。
|
||||
//
|
||||
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
|
||||
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
|
||||
// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。
|
||||
// SyncFromRemote 同步FromRemote。
|
||||
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
|
||||
cookieID = strings.TrimSpace(cookieID)
|
||||
if cookieID == "" {
|
||||
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
|
||||
}
|
||||
|
||||
// remoteIDs 用于本次流程后续判断的remoteIDs
|
||||
remoteIDs := make(map[string]struct{}, len(rows))
|
||||
// validRows 用于本次流程后续判断的有效Rows
|
||||
validRows := make([]ItemInfoRow, 0, len(rows))
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range rows {
|
||||
row.CookieID = cookieID
|
||||
row.ItemID = strings.TrimSpace(row.ItemID)
|
||||
if row.ItemID == "" {
|
||||
continue
|
||||
}
|
||||
if // exists 用于本次流程后续判断的exists
|
||||
_, exists := remoteIDs[row.ItemID]; exists {
|
||||
continue
|
||||
}
|
||||
remoteIDs[row.ItemID] = struct{}{}
|
||||
validRows = append(validRows, row)
|
||||
}
|
||||
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := i.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
// rollback 用于本次流程后续判断的rollback
|
||||
rollback := func(err error) (ItemSyncResult, error) {
|
||||
_ = tx.Rollback()
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
// index 表示当前遍历过程中的index
|
||||
for index := range validRows {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if validRows[index].IsMultiSpec {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
|
||||
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// args 用于本次流程后续判断的args
|
||||
args := make([]any, 0, len(remoteIDs)+1)
|
||||
args = append(args, cookieID)
|
||||
// deleteQuery 用于本次流程后续判断的delete查询
|
||||
deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL`
|
||||
if len(remoteIDs) > 0 {
|
||||
// placeholders 用于本次流程后续判断的placeholders
|
||||
placeholders := make([]string, 0, len(remoteIDs))
|
||||
// itemID 表示当前遍历过程中的商品ID
|
||||
for itemID := range remoteIDs {
|
||||
placeholders = append(placeholders, "?")
|
||||
args = append(args, itemID)
|
||||
}
|
||||
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
|
||||
}
|
||||
// deletedResult、err 用于本次流程后续判断的deletedResult、err
|
||||
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
// deleted、err 用于本次流程后续判断的deleted、err
|
||||
deleted, err := deletedResult.RowsAffected()
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
// ruleArgs 用于本次流程后续判断的规则Args
|
||||
ruleArgs := make([]any, 0, len(remoteIDs)+1)
|
||||
ruleArgs = append(ruleArgs, cookieID)
|
||||
// ruleQuery 用于本次流程后续判断的规则查询
|
||||
ruleQuery := `UPDATE automation_rules
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL`
|
||||
if len(remoteIDs) > 0 {
|
||||
// placeholders 用于本次流程后续判断的placeholders
|
||||
placeholders := make([]string, 0, len(remoteIDs))
|
||||
// itemID 表示当前遍历过程中的商品ID
|
||||
for itemID := range remoteIDs {
|
||||
placeholders = append(placeholders, "?")
|
||||
ruleArgs = append(ruleArgs, itemID)
|
||||
}
|
||||
ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tx.Commit(); err != nil {
|
||||
return ItemSyncResult{}, err
|
||||
}
|
||||
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
|
||||
}
|
||||
|
||||
// upsertBasic 封装upsertBasic业务协调。
|
||||
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
|
||||
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
|
||||
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
|
||||
// conflictClause 用于本次流程后续判断的conflictClause
|
||||
var conflictClause string
|
||||
switch i.Dialect {
|
||||
case DialectMySQL:
|
||||
conflictClause = ` ON DUPLICATE KEY UPDATE
|
||||
item_title=CASE WHEN VALUES(item_title) IS NOT NULL AND VALUES(item_title) != '' THEN VALUES(item_title) ELSE item_info.item_title END,
|
||||
item_description=CASE WHEN VALUES(item_description) IS NOT NULL AND VALUES(item_description) != '' THEN VALUES(item_description) ELSE item_info.item_description END,
|
||||
item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END,
|
||||
item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END,
|
||||
item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END,
|
||||
deleted_at=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP`
|
||||
default:
|
||||
conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET
|
||||
item_title=CASE WHEN EXCLUDED.item_title IS NOT NULL AND EXCLUDED.item_title != '' THEN EXCLUDED.item_title ELSE item_info.item_title END,
|
||||
item_description=CASE WHEN EXCLUDED.item_description IS NOT NULL AND EXCLUDED.item_description != '' THEN EXCLUDED.item_description ELSE item_info.item_description END,
|
||||
item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END,
|
||||
item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END,
|
||||
item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END,
|
||||
deleted_at=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP`
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := execer.ExecContext(ctx,
|
||||
`INSERT INTO item_info (cookie_id, item_id, item_title, item_description,
|
||||
item_category, item_price, item_detail, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+conflictClause,
|
||||
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
|
||||
nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail))
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。
|
||||
func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := i.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE item_info
|
||||
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE automation_rules
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// SetMultiSpec 设置多规格开关。
|
||||
func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
|
||||
boolToInt(on), cookieID, itemID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetMultiQuantity 设置多数量发货开关。
|
||||
func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := i.DB.ExecContext(ctx,
|
||||
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
|
||||
boolToInt(on), cookieID, itemID)
|
||||
return err
|
||||
}
|
||||
+21
-9
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -85,18 +86,15 @@ func (c *secretCodec) encrypt(scope, owner, value string) (string, error) {
|
||||
// 已加密行同时用于校验当前密钥,错误密钥会在启动业务 worker 前失败。
|
||||
// EncryptLegacySecrets 封装EncryptLegacySecrets业务协调。
|
||||
func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
|
||||
if s == nil || s.DB == nil {
|
||||
return nil
|
||||
}
|
||||
// codec 用于本次流程后续判断的codec
|
||||
codec := s.Cookies.codec
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
// codec、tx、err 是本次迁移使用的加密器、唯一事务边界及其打开错误。
|
||||
codec, tx, err := s.beginSecretMigration(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tx == nil {
|
||||
return nil
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// cookieSecret 用于本次流程后续判断的登录凭证Secret
|
||||
type cookieSecret struct{ id, value, password, metadata string }
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
@@ -144,7 +142,6 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tokenSecret 用于本次流程后续判断的令牌Secret
|
||||
type tokenSecret struct{ cookieID, deviceID, accessToken string }
|
||||
rows, err = tx.QueryContext(ctx, `SELECT cookie_id,device_id,access_token FROM account_tokens`)
|
||||
@@ -269,6 +266,21 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// beginSecretMigration 在不暴露部分可见状态前创建敏感字段升级所需的单一数据库事务。
|
||||
func (s *Store) beginSecretMigration(ctx context.Context) (*secretCodec, *sql.Tx, error) {
|
||||
if s == nil || s.DB == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
// codec 是 Store 已配置的数据密钥编解码器;tx 是覆盖所有旧凭证升级的原子事务。
|
||||
codec := s.Cookies.codec
|
||||
// tx 是覆盖全部旧秘密字段的原子事务;err 保存事务创建失败原因。
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return codec, tx, nil
|
||||
}
|
||||
|
||||
// decrypt 封装decrypt业务协调。
|
||||
func (c *secretCodec) decrypt(scope, owner, value string) (string, error) {
|
||||
if !strings.HasPrefix(value, encryptedValuePrefix) {
|
||||
|
||||
@@ -687,229 +687,3 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
|
||||
// not reuse the persisted accessToken. Official web reconnects always invoke
|
||||
// the login.token API before /reg.
|
||||
// acquireToken 封装acquire令牌业务协调。
|
||||
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
|
||||
return a.acquireTokenWithMinGap(ctx, false)
|
||||
}
|
||||
|
||||
// acquireRuntimeToken is retained as a compatibility wrapper for focused
|
||||
// tests and older internal callers. It follows the same fresh-token rule.
|
||||
// acquireRuntimeToken 封装acquireRuntime令牌业务协调。
|
||||
func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) {
|
||||
return a.acquireFreshConnectionToken(ctx)
|
||||
}
|
||||
|
||||
// acquireTokenWithMinGap 封装acquire令牌WithMinGap业务协调。
|
||||
func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
|
||||
// Invalidate any access token left by an older process/attempt before asking
|
||||
// MTOP for the token that will be bound to this connection.
|
||||
a.clearTokenCache(ctx)
|
||||
return a.refreshToken(ctx)
|
||||
}
|
||||
|
||||
// setLastTokenStatus 封装setLast令牌状态业务协调。
|
||||
func (c *credentialCoordinator) setLastTokenStatus(status string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有刷新诊断状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.lastTokenStatus = status
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// classifyTokenFailure 封装classify令牌Failure业务协调。
|
||||
func classifyTokenFailure(err error) string {
|
||||
if err == nil {
|
||||
return tokenRefreshFailedAPI
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
return tokenRefreshFailedSession
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || strings.Contains(strings.ToLower(err.Error()), "timeout") || strings.Contains(err.Error(), "超时") {
|
||||
return tokenRefreshFailedTimeout
|
||||
}
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "network") || strings.Contains(msg, "connection") || strings.Contains(msg, "请求失败") {
|
||||
return tokenRefreshFailedNetwork
|
||||
}
|
||||
return tokenRefreshFailedAPI
|
||||
}
|
||||
|
||||
// tokenFailureIsNonCounted 封装令牌FailureIsNonCounted业务协调。
|
||||
func tokenFailureIsNonCounted(status string) bool {
|
||||
switch status {
|
||||
case tokenRefreshFailedCaptcha, tokenRefreshFailedCaptchaError, tokenRefreshSkippedCooldown:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
|
||||
func (a *Account) RuntimeStatus() RuntimeStatus {
|
||||
a.runtimeMu.Lock()
|
||||
// state 是当前运行状态枚举快照。
|
||||
state := a.runtimeState
|
||||
// message 是当前运行状态说明快照。
|
||||
message := a.runtimeMessage
|
||||
// connected 是当前连接存在且状态为 online 的快照。
|
||||
connected := a.conn != nil && a.runtimeState == RuntimeOnline
|
||||
// failures 是连续连接失败次数快照。
|
||||
failures := a.connFailures
|
||||
// updatedAt 是状态最近更新时间快照。
|
||||
updatedAt := a.runtimeUpdatedAt
|
||||
a.runtimeMu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
// remaining 用于本次流程后续判断的remaining
|
||||
remaining := int64(0)
|
||||
if !a.tokenExpiresAt.IsZero() {
|
||||
remaining = int64(time.Until(a.tokenExpiresAt).Seconds())
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
}
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := RuntimeStatus{
|
||||
State: state,
|
||||
Message: message,
|
||||
Connected: connected,
|
||||
Failures: failures,
|
||||
UpdatedAt: updatedAt,
|
||||
TokenAcquiredAt: a.tokenAcquiredAt,
|
||||
TokenExpiresAt: a.tokenExpiresAt,
|
||||
TokenRefreshAt: a.tokenRefreshAt,
|
||||
TokenRemainingSeconds: remaining,
|
||||
TokenRefreshStatus: a.lastTokenStatus,
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return status
|
||||
}
|
||||
|
||||
// recordMessageReceived 更新最近收到消息时间,供 messageDispatcher 使用。
|
||||
func (a *Account) recordMessageReceived(receivedAt time.Time) {
|
||||
a.runtimeMu.Lock()
|
||||
a.lastMsgReceived = receivedAt
|
||||
a.runtimeMu.Unlock()
|
||||
}
|
||||
|
||||
// tokenRetryDelay 封装令牌重试延迟业务协调。
|
||||
func (a *Account) tokenRetryDelay() time.Duration {
|
||||
a.mu.Lock()
|
||||
// expiresAt 用于本次流程后续判断的expiresAt
|
||||
expiresAt := a.tokenExpiresAt
|
||||
// failures 用于本次流程后续判断的failures
|
||||
failures := a.tokenFetchFailures
|
||||
a.mu.Unlock()
|
||||
// delay 用于本次流程后续判断的延迟
|
||||
delay := time.Minute
|
||||
if failures > 1 {
|
||||
delay = 2 * time.Minute
|
||||
}
|
||||
if !expiresAt.IsZero() && time.Until(expiresAt) <= 2*time.Minute {
|
||||
delay = 30 * time.Second
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// notifyTransportReady 封装notifyTransportReady业务协调。
|
||||
func (a *Account) notifyTransportReady(ctx context.Context) {
|
||||
if // handler、ok 用于本次流程后续判断的handler、ok
|
||||
handler, ok := a.handler.(transportReadyHandler); ok {
|
||||
handler.OnTransportReady(ctx, a.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// setRuntimeState 封装setRuntime状态业务协调。
|
||||
func (a *Account) setRuntimeState(state, message string) {
|
||||
a.runtimeMu.Lock()
|
||||
defer a.runtimeMu.Unlock()
|
||||
a.runtimeState = state
|
||||
a.runtimeMessage = message
|
||||
a.runtimeUpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
// setRuntimeError 封装setRuntime错误业务协调。
|
||||
func (a *Account) setRuntimeError(ctx context.Context, err error) {
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(errString(err))
|
||||
a.runtimeMu.Lock()
|
||||
// prev 用于本次流程后续判断的prev
|
||||
prev := a.runtimeState
|
||||
a.runtimeMu.Unlock()
|
||||
switch {
|
||||
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
|
||||
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
|
||||
// 仅在从非验证状态转入时告警一次,避免重复刷屏。
|
||||
if prev != RuntimeVerificationRequired {
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/短信/人脸等)。系统可能无法自动恢复,请前往后台扫码完成验证。")
|
||||
}
|
||||
case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"):
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
|
||||
default:
|
||||
a.setRuntimeState(RuntimeReconnecting, "连接异常,系统将在限速后自动重试")
|
||||
}
|
||||
}
|
||||
|
||||
// SendText 通过当前 WebSocket 给买家发送文本消息。
|
||||
func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) error {
|
||||
return a.outgoing.sendText(ctx, chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// MarkChatRead 向已连接的 WebSocket 上报会话消息已读状态,调用方负责用户所有权校验。
|
||||
func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error {
|
||||
// conn、err 保存当前连接快照及不可发送时的生命周期错误。
|
||||
conn, _, err := a.outgoing.currentSenderState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// readCtx、cancel 为平台上报设置固定超时,取消责任在本方法返回时释放。
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
// reader、ok 保存连接是否支持可选的已读上报能力。
|
||||
reader, ok := conn.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
})
|
||||
if !ok {
|
||||
return fmt.Errorf("当前 WebSocket 不支持已读上报")
|
||||
}
|
||||
return reader.MarkChatRead(readCtx, chatID, messageIDs)
|
||||
}
|
||||
|
||||
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
|
||||
// width/height 为图片真实尺寸,单位为像素;传入非正值时由 WebSocket 使用默认尺寸。
|
||||
func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, width, height int) error {
|
||||
return a.outgoing.sendImage(ctx, chatID, toUserID, imageURL, cardID, width, height)
|
||||
}
|
||||
|
||||
// FetchChatHistory reuses the account's registered IM connection. Keeping this
|
||||
// optional capability outside WSConn avoids forcing non-chat test transports to
|
||||
// implement history retrieval.
|
||||
// FetchChatHistory 封装Fetch聊天History业务协调。
|
||||
func (a *Account) FetchChatHistory(ctx context.Context, chatID string, cursor int64, limit int) (map[string]any, string, error) {
|
||||
return a.outgoing.fetchChatHistory(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
// FetchChatConversations 封装Fetch聊天Conversations业务协调。
|
||||
func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limit int) (map[string]any, string, error) {
|
||||
return a.outgoing.fetchChatConversations(ctx, cursor, limit)
|
||||
}
|
||||
|
||||
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
|
||||
func (a *Account) AutomationReady() bool {
|
||||
return a.outgoing.automationReady()
|
||||
}
|
||||
|
||||
// rotatePageDeviceID 对应官网 auto-login 成功后的 location.reload():
|
||||
// 新 FishEngine 使用新的 UUID-userID,普通 Set-Cookie 与自然重连不会调用它。
|
||||
// rotatePageDeviceID 封装rotate页码DeviceID业务协调。
|
||||
func (a *Account) rotatePageDeviceID() {
|
||||
a.mu.Lock()
|
||||
// userID 用于本次流程后续判断的用户ID
|
||||
userID := a.UserID
|
||||
if userID == "" {
|
||||
userID = protocol.TransCookies(a.CookieStr)["unb"]
|
||||
}
|
||||
a.deviceID = protocol.GenerateDeviceID(userID)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// acquireToken 为当前账号取得连接级 Token 与其绑定 Cookie 快照,供 WebSocket 注册使用。
|
||||
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
|
||||
return a.acquireTokenWithMinGap(ctx, false)
|
||||
}
|
||||
|
||||
// acquireRuntimeToken is retained as a compatibility wrapper for focused
|
||||
// tests and older internal callers. It follows the same fresh-token rule.
|
||||
// acquireRuntimeToken 封装acquireRuntime令牌业务协调。
|
||||
func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) {
|
||||
return a.acquireFreshConnectionToken(ctx)
|
||||
}
|
||||
|
||||
// acquireTokenWithMinGap 封装acquire令牌WithMinGap业务协调。
|
||||
func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
|
||||
// Invalidate any access token left by an older process/attempt before asking
|
||||
// MTOP for the token that will be bound to this connection.
|
||||
a.clearTokenCache(ctx)
|
||||
return a.refreshToken(ctx)
|
||||
}
|
||||
|
||||
// setLastTokenStatus 封装setLast令牌状态业务协调。
|
||||
func (c *credentialCoordinator) setLastTokenStatus(status string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有刷新诊断状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.lastTokenStatus = status
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// classifyTokenFailure 封装classify令牌Failure业务协调。
|
||||
func classifyTokenFailure(err error) string {
|
||||
if err == nil {
|
||||
return tokenRefreshFailedAPI
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
return tokenRefreshFailedSession
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || strings.Contains(strings.ToLower(err.Error()), "timeout") || strings.Contains(err.Error(), "超时") {
|
||||
return tokenRefreshFailedTimeout
|
||||
}
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "network") || strings.Contains(msg, "connection") || strings.Contains(msg, "请求失败") {
|
||||
return tokenRefreshFailedNetwork
|
||||
}
|
||||
return tokenRefreshFailedAPI
|
||||
}
|
||||
|
||||
// tokenFailureIsNonCounted 封装令牌FailureIsNonCounted业务协调。
|
||||
func tokenFailureIsNonCounted(status string) bool {
|
||||
switch status {
|
||||
case tokenRefreshFailedCaptcha, tokenRefreshFailedCaptchaError, tokenRefreshSkippedCooldown:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
|
||||
func (a *Account) RuntimeStatus() RuntimeStatus {
|
||||
a.runtimeMu.Lock()
|
||||
// state 是当前运行状态枚举快照。
|
||||
state := a.runtimeState
|
||||
// message 是当前运行状态说明快照。
|
||||
message := a.runtimeMessage
|
||||
// connected 是当前连接存在且状态为 online 的快照。
|
||||
connected := a.conn != nil && a.runtimeState == RuntimeOnline
|
||||
// failures 是连续连接失败次数快照。
|
||||
failures := a.connFailures
|
||||
// updatedAt 是状态最近更新时间快照。
|
||||
updatedAt := a.runtimeUpdatedAt
|
||||
a.runtimeMu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
// remaining 用于本次流程后续判断的remaining
|
||||
remaining := int64(0)
|
||||
if !a.tokenExpiresAt.IsZero() {
|
||||
remaining = int64(time.Until(a.tokenExpiresAt).Seconds())
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
}
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := RuntimeStatus{
|
||||
State: state,
|
||||
Message: message,
|
||||
Connected: connected,
|
||||
Failures: failures,
|
||||
UpdatedAt: updatedAt,
|
||||
TokenAcquiredAt: a.tokenAcquiredAt,
|
||||
TokenExpiresAt: a.tokenExpiresAt,
|
||||
TokenRefreshAt: a.tokenRefreshAt,
|
||||
TokenRemainingSeconds: remaining,
|
||||
TokenRefreshStatus: a.lastTokenStatus,
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return status
|
||||
}
|
||||
|
||||
// recordMessageReceived 更新最近收到消息时间,供 messageDispatcher 使用。
|
||||
func (a *Account) recordMessageReceived(receivedAt time.Time) {
|
||||
a.runtimeMu.Lock()
|
||||
a.lastMsgReceived = receivedAt
|
||||
a.runtimeMu.Unlock()
|
||||
}
|
||||
|
||||
// tokenRetryDelay 封装令牌重试延迟业务协调。
|
||||
func (a *Account) tokenRetryDelay() time.Duration {
|
||||
a.mu.Lock()
|
||||
// expiresAt 用于本次流程后续判断的expiresAt
|
||||
expiresAt := a.tokenExpiresAt
|
||||
// failures 用于本次流程后续判断的failures
|
||||
failures := a.tokenFetchFailures
|
||||
a.mu.Unlock()
|
||||
// delay 用于本次流程后续判断的延迟
|
||||
delay := time.Minute
|
||||
if failures > 1 {
|
||||
delay = 2 * time.Minute
|
||||
}
|
||||
if !expiresAt.IsZero() && time.Until(expiresAt) <= 2*time.Minute {
|
||||
delay = 30 * time.Second
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// notifyTransportReady 封装notifyTransportReady业务协调。
|
||||
func (a *Account) notifyTransportReady(ctx context.Context) {
|
||||
if // handler、ok 用于本次流程后续判断的handler、ok
|
||||
handler, ok := a.handler.(transportReadyHandler); ok {
|
||||
handler.OnTransportReady(ctx, a.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// setRuntimeState 封装setRuntime状态业务协调。
|
||||
func (a *Account) setRuntimeState(state, message string) {
|
||||
a.runtimeMu.Lock()
|
||||
defer a.runtimeMu.Unlock()
|
||||
a.runtimeState = state
|
||||
a.runtimeMessage = message
|
||||
a.runtimeUpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
// setRuntimeError 封装setRuntime错误业务协调。
|
||||
func (a *Account) setRuntimeError(ctx context.Context, err error) {
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.ToLower(errString(err))
|
||||
a.runtimeMu.Lock()
|
||||
// prev 用于本次流程后续判断的prev
|
||||
prev := a.runtimeState
|
||||
a.runtimeMu.Unlock()
|
||||
switch {
|
||||
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
|
||||
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
|
||||
// 仅在从非验证状态转入时告警一次,避免重复刷屏。
|
||||
if prev != RuntimeVerificationRequired {
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/短信/人脸等)。系统可能无法自动恢复,请前往后台扫码完成验证。")
|
||||
}
|
||||
case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"):
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
|
||||
default:
|
||||
a.setRuntimeState(RuntimeReconnecting, "连接异常,系统将在限速后自动重试")
|
||||
}
|
||||
}
|
||||
|
||||
// SendText 通过当前 WebSocket 给买家发送文本消息。
|
||||
func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) error {
|
||||
return a.outgoing.sendText(ctx, chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// MarkChatRead 向已连接的 WebSocket 上报会话消息已读状态,调用方负责用户所有权校验。
|
||||
func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error {
|
||||
// conn、err 保存当前连接快照及不可发送时的生命周期错误。
|
||||
conn, _, err := a.outgoing.currentSenderState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// readCtx、cancel 为平台上报设置固定超时,取消责任在本方法返回时释放。
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
// reader、ok 保存连接是否支持可选的已读上报能力。
|
||||
reader, ok := conn.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
})
|
||||
if !ok {
|
||||
return fmt.Errorf("当前 WebSocket 不支持已读上报")
|
||||
}
|
||||
return reader.MarkChatRead(readCtx, chatID, messageIDs)
|
||||
}
|
||||
|
||||
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
|
||||
// width/height 为图片真实尺寸,单位为像素;传入非正值时由 WebSocket 使用默认尺寸。
|
||||
func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, width, height int) error {
|
||||
return a.outgoing.sendImage(ctx, chatID, toUserID, imageURL, cardID, width, height)
|
||||
}
|
||||
|
||||
// FetchChatHistory reuses the account's registered IM connection. Keeping this
|
||||
// optional capability outside WSConn avoids forcing non-chat test transports to
|
||||
// implement history retrieval.
|
||||
// FetchChatHistory 封装Fetch聊天History业务协调。
|
||||
func (a *Account) FetchChatHistory(ctx context.Context, chatID string, cursor int64, limit int) (map[string]any, string, error) {
|
||||
return a.outgoing.fetchChatHistory(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
// FetchChatConversations 封装Fetch聊天Conversations业务协调。
|
||||
func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limit int) (map[string]any, string, error) {
|
||||
return a.outgoing.fetchChatConversations(ctx, cursor, limit)
|
||||
}
|
||||
|
||||
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
|
||||
func (a *Account) AutomationReady() bool {
|
||||
return a.outgoing.automationReady()
|
||||
}
|
||||
|
||||
// rotatePageDeviceID 对应官网 auto-login 成功后的 location.reload():
|
||||
// 新 FishEngine 使用新的 UUID-userID,普通 Set-Cookie 与自然重连不会调用它。
|
||||
// rotatePageDeviceID 封装rotate页码DeviceID业务协调。
|
||||
func (a *Account) rotatePageDeviceID() {
|
||||
a.mu.Lock()
|
||||
// userID 用于本次流程后续判断的用户ID
|
||||
userID := a.UserID
|
||||
if userID == "" {
|
||||
userID = protocol.TransCookies(a.CookieStr)["unb"]
|
||||
}
|
||||
a.deviceID = protocol.GenerateDeviceID(userID)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
@@ -40,28 +40,14 @@ func (c *connectionCoordinator) run(parent context.Context) error {
|
||||
defer shutdownCancel()
|
||||
c.waitForOwnedWorkers(shutdownCtx)
|
||||
}()
|
||||
// lifecycleStarted 表示 Stop 是否已经在 Run 建立生命周期前完成;false 时必须放弃迟到启动。
|
||||
lifecycleStarted := a.lifecycle.start(ctx, cancel)
|
||||
if !lifecycleStarted {
|
||||
return context.Canceled
|
||||
// shouldConnect、setupErr 分别表示账号是否仍可启动连接循环及启动准备失败原因。
|
||||
shouldConnect, setupErr := c.prepareRun(ctx, cancel)
|
||||
if setupErr != nil {
|
||||
return setupErr
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
|
||||
a.logger.Info("账号在启动续期前已禁用")
|
||||
if !shouldConnect {
|
||||
return nil
|
||||
}
|
||||
a.startWSRecorder(ctx)
|
||||
// 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建
|
||||
// FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时
|
||||
// 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS;
|
||||
// Chromium 仅用于读取本机指纹和处理 token 滑块。
|
||||
if a.renewer != nil {
|
||||
if a.tryAPIRenew(ctx) {
|
||||
a.rotatePageDeviceID()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
@@ -98,58 +84,15 @@ func (c *connectionCoordinator) run(parent context.Context) error {
|
||||
// token、cookieStr、err 保存本次连接专用 Token、其绑定 Cookie 快照与获取错误。
|
||||
token, cookieStr, err := a.acquireFreshConnectionToken(ctx)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
// retry、failureErr 分别表示本轮应否重试及必须终止账号循环的错误。
|
||||
retry, failureErr := c.handleTokenAcquisitionFailure(ctx, conn, err)
|
||||
if failureErr != nil {
|
||||
return failureErr
|
||||
}
|
||||
a.logger.Error("获取 token 失败", "err", err)
|
||||
a.mu.Lock()
|
||||
// status 是刷新失败分类快照,用于决定是否累加失败计数。
|
||||
status := a.lastTokenStatus
|
||||
// nonCounted 表示验证码与冷却失败不计入连接 Token 获取失败次数。
|
||||
nonCounted := tokenFailureIsNonCounted(status)
|
||||
if !nonCounted {
|
||||
a.tokenFetchFailures++
|
||||
if retry {
|
||||
continue
|
||||
}
|
||||
// tokenFailures 是当前失败次数快照,只用于保留原有诊断路径。
|
||||
tokenFailures := a.tokenFetchFailures
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeError(ctx, err)
|
||||
_ = tokenFailures // 仅用于诊断;官网不会按次数永久禁用账号。
|
||||
if mtop.IsRiskVerificationErr(err) {
|
||||
a.logger.Warn("闲鱼要求安全验证,停止本次消息登录", "err", err)
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
|
||||
"账号触发闲鱼风控验证(滑块/人脸等),需要重新登录或完成人工验证。")
|
||||
return err
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
// reason 是当前凭证失效或恢复失败时展示给运行状态与通知的原因。
|
||||
reason := "登录凭证已失效,正在立即续期"
|
||||
a.logger.Warn("token API 检测到 Session 过期,停止重试并开始即时续期", "err", err)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeReconnecting, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
|
||||
a.reloadCookieFromDB(ctx)
|
||||
a.clearCurrentToken()
|
||||
a.resetFailures()
|
||||
a.setRuntimeState(RuntimeConnecting, "Session 续期成功,正在重新连接")
|
||||
continue
|
||||
}
|
||||
reason = "登录凭证已失效,自动续期失败,请重新扫码登录"
|
||||
a.setRuntimeState(RuntimeAuthExpired, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
return err
|
||||
}
|
||||
// 网络或服务端瞬时错误不能让账号运行时永久退出。只要登录 Session
|
||||
// 没有明确失效,就持续重试获取连接级 Token。
|
||||
a.setRuntimeState(RuntimeReconnecting, "获取消息凭证失败,正在重试")
|
||||
a.notifyOffline(ctx, "获取消息凭证失败,正在自动重试:"+errString(err))
|
||||
// sleepErr 是本次重试退避等待被取消或到期时返回的错误。
|
||||
if sleepErr := sleepCtx(ctx, a.tokenRetryDelay()); sleepErr != nil {
|
||||
return sleepErr
|
||||
}
|
||||
continue
|
||||
return nil
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.currentToken = token
|
||||
@@ -186,26 +129,7 @@ func (c *connectionCoordinator) run(parent context.Context) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.runtimeMu.Lock()
|
||||
a.conn = conn
|
||||
a.connStartedAt = time.Now()
|
||||
a.connFailures = 0
|
||||
a.networkFailures = 0
|
||||
a.authExpiredAlerted = false // 连接成功,复位 auth_expired 告警标记
|
||||
// shouldRecovered 表示本次连接是否结束了一个已告警的离线周期。
|
||||
shouldRecovered := a.offlineNotified
|
||||
// offlineSince 是本次恢复前离线周期的起始时间快照。
|
||||
offlineSince := a.offlineSince
|
||||
a.offlineNotified = false
|
||||
a.offlineSince = time.Time{}
|
||||
a.lastOfflineReason = ""
|
||||
a.runtimeMu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
a.notifyTransportReady(ctx)
|
||||
if shouldRecovered {
|
||||
a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线",
|
||||
fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince)))
|
||||
}
|
||||
c.markConnectionOnline(ctx, conn)
|
||||
|
||||
// 3) 健康连接维持心跳和收包,并在服务端 Token 过期前主动关闭,
|
||||
// 进入下一轮连接以重新调用 Token API 和 /reg。
|
||||
@@ -278,6 +202,106 @@ func (c *connectionCoordinator) run(parent context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
// prepareRun 建立账号生命周期、记录 worker 并执行首次 API 续期;返回 false 表示账号已禁用。
|
||||
func (c *connectionCoordinator) prepareRun(ctx context.Context, cancel context.CancelFunc) (bool, error) {
|
||||
// a 是当前连接协调器绑定的账号 facade;生命周期只能在它完整构造后开始。
|
||||
a := c.account
|
||||
if !a.lifecycle.start(ctx, cancel) {
|
||||
return false, context.Canceled
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
|
||||
a.logger.Info("账号在启动续期前已禁用")
|
||||
return false, nil
|
||||
}
|
||||
a.startWSRecorder(ctx)
|
||||
if a.renewer != nil {
|
||||
if a.tryAPIRenew(ctx) {
|
||||
a.rotatePageDeviceID()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// markConnectionOnline 原子记录新连接并发布恢复事件,避免连接循环混入状态收口细节。
|
||||
func (c *connectionCoordinator) markConnectionOnline(ctx context.Context, conn WSConn) {
|
||||
// a 是当前连接协调器绑定的账号 facade;shouldRecovered 和 offlineSince 是锁内采集的离线周期快照。
|
||||
a := c.account
|
||||
a.runtimeMu.Lock()
|
||||
a.conn = conn
|
||||
a.connStartedAt = time.Now()
|
||||
a.connFailures = 0
|
||||
a.networkFailures = 0
|
||||
a.authExpiredAlerted = false
|
||||
// shouldRecovered 表示本次连接是否结束了一个已经通知用户的离线周期。
|
||||
shouldRecovered := a.offlineNotified
|
||||
// offlineSince 保存该离线周期起始时间,用于恢复通知中的持续时长诊断。
|
||||
offlineSince := a.offlineSince
|
||||
a.offlineNotified = false
|
||||
a.offlineSince = time.Time{}
|
||||
a.lastOfflineReason = ""
|
||||
a.runtimeMu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
a.notifyTransportReady(ctx)
|
||||
if shouldRecovered {
|
||||
a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线", fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince)))
|
||||
}
|
||||
}
|
||||
|
||||
// handleTokenAcquisitionFailure 关闭本轮连接并按风控、Session 失效或可重试网络错误决定后续动作。
|
||||
func (c *connectionCoordinator) handleTokenAcquisitionFailure(ctx context.Context, conn WSConn, tokenErr error) (bool, error) {
|
||||
// a 是协调器拥有的账号 facade;retry 为 true 时调用方必须重新执行一轮完整连接流程。
|
||||
a := c.account
|
||||
_ = conn.Close()
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
}
|
||||
a.logger.Error("获取 token 失败", "err", tokenErr)
|
||||
a.mu.Lock()
|
||||
// status 是本次失败的分类快照;nonCounted 表示验证码和冷却不会污染网络失败计数。
|
||||
status := a.lastTokenStatus
|
||||
// nonCounted 表示本次失败是否应排除在连接 Token 的失败计数之外。
|
||||
nonCounted := tokenFailureIsNonCounted(status)
|
||||
if !nonCounted {
|
||||
a.tokenFetchFailures++
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeError(ctx, tokenErr)
|
||||
if mtop.IsRiskVerificationErr(tokenErr) {
|
||||
a.logger.Warn("闲鱼要求安全验证,停止本次消息登录", "err", tokenErr)
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证", "账号触发闲鱼风控验证(滑块/人脸等),需要重新登录或完成人工验证。")
|
||||
return false, tokenErr
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(tokenErr) {
|
||||
// reason 是登录态恢复期间写入运行状态与通知的用户可见原因。
|
||||
reason := "登录凭证已失效,正在立即续期"
|
||||
a.logger.Warn("token API 检测到 Session 过期,停止重试并开始即时续期", "err", tokenErr)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeReconnecting, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(tokenErr))
|
||||
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
|
||||
a.reloadCookieFromDB(ctx)
|
||||
a.clearCurrentToken()
|
||||
a.resetFailures()
|
||||
a.setRuntimeState(RuntimeConnecting, "Session 续期成功,正在重新连接")
|
||||
return true, nil
|
||||
}
|
||||
reason = "登录凭证已失效,自动续期失败,请重新扫码登录"
|
||||
a.setRuntimeState(RuntimeAuthExpired, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(tokenErr))
|
||||
return false, tokenErr
|
||||
}
|
||||
a.setRuntimeState(RuntimeReconnecting, "获取消息凭证失败,正在重试")
|
||||
a.notifyOffline(ctx, "获取消息凭证失败,正在自动重试:"+errString(tokenErr))
|
||||
// sleepErr 保存退避等待被取消或超时的原因;该错误必须终止当前账号运行循环。
|
||||
if sleepErr := sleepCtx(ctx, a.tokenRetryDelay()); sleepErr != nil {
|
||||
return false, sleepErr
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// waitForOwnedWorkers 在 shutdownCtx 的总预算内等待连接协调器启动的 recorder 与迟到续期任务。
|
||||
// 两类任务都继承 Account.Run 的 Context;本方法只观察各自完成信号,不创建新的等待 goroutine。
|
||||
func (c *connectionCoordinator) waitForOwnedWorkers(shutdownCtx context.Context) {
|
||||
|
||||
@@ -2,16 +2,13 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
"xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
@@ -615,560 +612,3 @@ func (c *credentialCoordinator) notifyCredentialUpdated(ctx context.Context) {
|
||||
// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程
|
||||
// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。
|
||||
// refreshToken 封装refresh令牌业务协调。
|
||||
func (c *credentialCoordinator) refreshToken(ctx context.Context) (string, string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,保留连接流程使用的返回契约。
|
||||
a := c.account
|
||||
return a.refreshTokenWithMinGap(ctx, false)
|
||||
}
|
||||
|
||||
// refreshTokenWithMinGap 保留旧签名以避免影响调用方;参考实现没有额外的一分钟
|
||||
// Token 防抖,因此 enforceMinGap 不参与行为。
|
||||
// refreshTokenWithMinGap 封装refresh令牌WithMinGap业务协调。
|
||||
func (c *credentialCoordinator) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,集中访问 MTOP、Cookie repository 和状态。
|
||||
a := c.account
|
||||
// releaseRefreshGate 释放 Token 刷新占用的通道令牌。
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx)
|
||||
if gateErr != nil {
|
||||
return "", "", gateErr
|
||||
}
|
||||
defer releaseRefreshGate()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := func() {}
|
||||
// credentialLocked 标识当前调用是否持有账号凭证锁。
|
||||
credentialLocked := false
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
}
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// refreshGate 串行化完整 Token/Cookie 更新事务;风控失败冷却仍由调用方状态控制。
|
||||
if // remaining 用于本次流程后续判断的remaining
|
||||
remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 {
|
||||
a.setLastTokenStatus(tokenRefreshSkippedCooldown)
|
||||
return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second))
|
||||
}
|
||||
|
||||
a.reloadCookieFromDB(ctx)
|
||||
|
||||
a.mu.Lock()
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := a.CookieStr
|
||||
// metadataJSON 保存当前凭证快照对应的 metadata。
|
||||
metadataJSON := ""
|
||||
a.lastTokenRefresh = time.Now()
|
||||
a.lastTokenStatus = tokenRefreshStarted
|
||||
a.mu.Unlock()
|
||||
|
||||
// deviceID 用于本次流程后续判断的deviceID
|
||||
deviceID := strings.TrimSpace(a.deviceID)
|
||||
if deviceID == "" {
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
|
||||
deviceID = protocol.GenerateDeviceID(unb)
|
||||
a.mu.Lock()
|
||||
a.deviceID = deviceID
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// runtimeData 保存 Token 请求开始前的最小凭证快照。
|
||||
runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if detailErr != nil {
|
||||
return "", "", detailErr
|
||||
}
|
||||
cookieStr = runtimeData.Value
|
||||
metadataJSON = runtimeData.MetadataJSON
|
||||
}
|
||||
// Token 网络请求和风控恢复都必须在共享凭证锁外执行。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
for // captchaRetry 用于本次流程后续判断的captcha重试
|
||||
captchaRetry := 0; captchaRetry < 3; captchaRetry++ {
|
||||
// res 用于本次流程后续判断的响应
|
||||
var res *mtop.RefreshResult
|
||||
// err 用于本次流程后续判断的err
|
||||
var err error
|
||||
if // scoped、ok 用于本次流程后续判断的scoped、ok
|
||||
scoped, ok := a.mtop.(scopedTokenClient); ok {
|
||||
// snapshot 用于本次流程后续判断的snapshot
|
||||
var snapshot []cookierefresh.BrowserCookie
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if metadata, metadataErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID); metadataErr == nil { // metadata 是 token 请求所需的 Cookie 快照信息。
|
||||
snapshot = cookierefresh.SnapshotFromMetadata(metadata)
|
||||
}
|
||||
}
|
||||
res, err = scoped.RefreshTokenWithCredentialContext(ctx, cookieStr, deviceID, snapshot)
|
||||
} else {
|
||||
res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// credentialUnlock 保存 Token 响应提交临界区的释放函数。
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
// latestRuntimeData 和 reloadErr 保存网络请求完成后的最新凭证视图及重读错误。
|
||||
latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if reloadErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
return "", "", reloadErr
|
||||
}
|
||||
if latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON {
|
||||
// 并发流程已经更新凭证,丢弃旧请求的 Token 和 Cookie 响应,下一轮使用最新快照重试。
|
||||
cookieStr = latestRuntimeData.Value
|
||||
metadataJSON = latestRuntimeData.MetadataJSON
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
continue
|
||||
}
|
||||
}
|
||||
// 参考实现无论业务结果为何,都先合并响应 Set-Cookie。本地还必须先把
|
||||
// 完整 Jar 持久化成功,避免当前 /reg 成功而下次重连回滚到旧凭证。
|
||||
// 响应处理会广播给 Handler,因此先释放凭证锁,成功 Token 绑定前会重新校验。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
// persistErr 用于本次流程后续判断的persistErr
|
||||
var persistErr error
|
||||
cookieStr, persistErr = a.adoptTokenResponseCookies(ctx, cookieStr, res)
|
||||
if persistErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
return "", "", fmt.Errorf("保存 token 响应 Cookie: %w", persistErr)
|
||||
}
|
||||
if err != nil && mtop.IsRiskVerificationErr(err) {
|
||||
// 风控恢复是外部调用,不能在共享凭证锁内执行。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
if // recovered、ok 用于本次流程后续判断的recovered、ok
|
||||
recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, err); ok {
|
||||
cookieStr = recovered.UpdatedCookies
|
||||
// 重取地址时即使拿到了 accessToken,参考实现也不会直接采用;
|
||||
// 它会清缓存后重新走一次标准 token 请求。
|
||||
continue
|
||||
}
|
||||
a.markTokenCaptchaFailure()
|
||||
a.setLastTokenStatus(tokenRefreshFailedCaptcha)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", err
|
||||
}
|
||||
if err != nil {
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := classifyTokenFailure(err)
|
||||
a.setLastTokenStatus(status)
|
||||
a.clearCurrentToken()
|
||||
if status != tokenRefreshFailedNetwork && status != tokenRefreshFailedTimeout {
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
if res == nil || strings.TrimSpace(res.AccessToken) == "" {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("token API 未返回结果")
|
||||
}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
}
|
||||
// credentialFP、fingerprintErr 用于本次流程后续判断的credentialFP、fingerprintErr
|
||||
credentialFP, fingerprintErr := a.databaseCredentialFingerprint(ctx, cookieStr)
|
||||
if fingerprintErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("绑定 token 凭证状态: %w", fingerprintErr)
|
||||
}
|
||||
a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, credentialFP)
|
||||
a.mu.Lock()
|
||||
a.credentialFP = credentialFP
|
||||
a.tokenCredentialFP = credentialFP
|
||||
a.lastCaptchaFailure = time.Time{}
|
||||
a.tokenFetchFailures = 0
|
||||
a.lastTokenStatus = tokenRefreshSuccess
|
||||
a.mu.Unlock()
|
||||
a.runtimeMu.Lock()
|
||||
a.lastMsgReceived = time.Time{}
|
||||
a.runtimeMu.Unlock()
|
||||
return res.AccessToken, cookieStr, nil
|
||||
}
|
||||
|
||||
a.setLastTokenStatus(tokenRefreshFailedCaptcha)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("滑块验证重试次数已达上限")
|
||||
}
|
||||
|
||||
// clearCurrentToken 封装clearCurrent令牌业务协调。
|
||||
func (c *credentialCoordinator) clearCurrentToken() {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有 Token 状态锁。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.currentToken = ""
|
||||
a.tokenCredentialFP = ""
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// adoptTokenResponseCookies 封装adopt令牌响应Cookies业务协调。
|
||||
func (c *credentialCoordinator) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) (string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Cookie 持久化与回调端口。
|
||||
a := c.account
|
||||
if res == nil {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if !res.CookieSnapshotComplete && !res.CookieStateChanged && strings.TrimSpace(res.UpdatedCookies) == "" {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if !res.CookieSnapshotComplete && !res.CookieStateChanged && res.UpdatedCookies == cookieStr && len(res.CookieSnapshot) == 0 {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
metadata, detailErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含 token 响应 Cookie 合并所需的快照信息。
|
||||
if detailErr != nil {
|
||||
return cookieStr, detailErr
|
||||
}
|
||||
// metadata 已在 repository 层按账号作用域解密,不读取旧 Cookie 或登录秘密。
|
||||
// 下面继续根据响应类型合并已有快照,并由 UpdateRenewalCookie 统一持久化。
|
||||
// 错误返回和运行时状态更新顺序保持原有 token 响应语义。
|
||||
// 只有 token 响应本身发生变化时才进入后续快照合并逻辑。
|
||||
if res.CookieSnapshotComplete {
|
||||
// snapshot 用于本次流程后续判断的snapshot
|
||||
snapshot := cookierefresh.NormalizeSnapshot(res.CookieSnapshot)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
|
||||
} else if // snapshot、snapshotOK 用于本次流程后续判断的snapshot、snapshotOK
|
||||
snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(metadata); snapshotOK {
|
||||
// 扁平结果不能凭空证明 Jar 完整;仅在已有权威 Jar 时按已知
|
||||
// Domain/Path 身份对值做兼容合并。
|
||||
snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies)
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
|
||||
} else {
|
||||
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return cookieStr, err
|
||||
}
|
||||
a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata))
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
return res.UpdatedCookies, nil
|
||||
}
|
||||
if res.UpdatedCookies != cookieStr {
|
||||
a.replaceCookieStr(res.UpdatedCookies)
|
||||
}
|
||||
return res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
// tryTokenCaptchaRecovery 封装try令牌CaptchaRecovery业务协调。
|
||||
func (c *credentialCoordinator) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, err error) (*mtop.RefreshResult, bool) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供风控 Handler 与运行时状态。
|
||||
a := c.account
|
||||
// h、ok 用于本次流程后续判断的h、ok
|
||||
h, ok := a.handler.(tokenCaptchaHandler)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
// riskErr 用于本次流程后续判断的riskErr
|
||||
var riskErr *mtop.RiskVerificationError
|
||||
if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" {
|
||||
return nil, false
|
||||
}
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证",
|
||||
"token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。")
|
||||
// result、ok 用于本次流程后续判断的result、ok
|
||||
result, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL, deviceID)
|
||||
if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
// updatedCookies、persistErr 用于本次流程后续判断的updatedCookies、persistErr
|
||||
updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result)
|
||||
if persistErr != nil {
|
||||
a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr)
|
||||
return nil, false
|
||||
}
|
||||
result.UpdatedCookies = updatedCookies
|
||||
a.replaceCookieStr(updatedCookies)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage)
|
||||
return result, true
|
||||
}
|
||||
|
||||
// markTokenCaptchaFailure 封装mark令牌CaptchaFailure业务协调。
|
||||
func (c *credentialCoordinator) markTokenCaptchaFailure() {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.lastCaptchaFailure = time.Now()
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// tokenCaptchaCooldownRemaining 封装令牌CaptchaCooldownRemaining业务协调。
|
||||
func (c *credentialCoordinator) tokenCaptchaCooldownRemaining() time.Duration {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
// lastFailure 用于本次流程后续判断的lastFailure
|
||||
lastFailure := a.lastCaptchaFailure
|
||||
a.mu.Unlock()
|
||||
if lastFailure.IsZero() {
|
||||
return 0
|
||||
}
|
||||
// remaining 用于本次流程后续判断的remaining
|
||||
remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure)
|
||||
if remaining < 0 {
|
||||
return 0
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
|
||||
// saveTokenCache records the server expiry and current page-runtime identity.
|
||||
// It is diagnostic state only: acquireToken never reads the accessToken back
|
||||
// for a later WebSocket registration.
|
||||
// saveTokenCache 封装save令牌Cache业务协调。
|
||||
func (c *credentialCoordinator) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Token repository 与诊断日志。
|
||||
a := c.account
|
||||
if accessToken == "" {
|
||||
return
|
||||
}
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now()
|
||||
// expiresAt、refreshAt 用于本次流程后续判断的expiresAt、refreshAt
|
||||
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
|
||||
// tokenFP 用于本次流程后续判断的令牌FP
|
||||
tokenFP := tokenFingerprint(accessToken)
|
||||
a.mu.Lock()
|
||||
// previousTokenFP 用于本次流程后续判断的previous令牌FP
|
||||
previousTokenFP := a.tokenFingerprint
|
||||
a.tokenFingerprint = tokenFP
|
||||
a.tokenAcquiredAt = now
|
||||
a.tokenExpiresAt = expiresAt
|
||||
a.tokenRefreshAt = refreshAt
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP)
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
// expireAt 用于本次流程后续判断的expireAt
|
||||
expireAt := effectiveTokenExpireAt(serverExpireAt, now)
|
||||
if expireAt == 0 {
|
||||
// 服务端未给有效期时仍使用保守运行时轮换时间,但不把推测期限
|
||||
// 伪装成服务端缓存期限。
|
||||
a.logger.Warn("token API 未返回可用过期时间,使用保守轮换时间", "refresh_at", refreshAt)
|
||||
a.clearTokenCache(ctx)
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialFP); err != nil {
|
||||
a.logger.Warn("缓存 accessToken 失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token,
|
||||
// 同时避免日志泄露可用于 WS 注册的凭证原文。
|
||||
// tokenFingerprint 封装令牌Fingerprint业务协调。
|
||||
func tokenFingerprint(token string) string {
|
||||
// sum 用于本次流程后续判断的sum
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return fmt.Sprintf("%x", sum[:6])
|
||||
}
|
||||
|
||||
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
|
||||
func (c *credentialCoordinator) clearTokenCache(ctx context.Context) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Token repository 与内存状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.tokenFingerprint = ""
|
||||
a.mu.Unlock()
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.Clear(ctx, a.CookieID); err != nil {
|
||||
a.logger.Warn("清除 token 缓存失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// databaseCredentialFingerprint returns the complete DB credential state that
|
||||
// produced cookieStr. It must be called while the account credential lock is
|
||||
// held when a Store is present.
|
||||
// databaseCredentialFingerprint 封装databaseCredentialFingerprint业务协调。
|
||||
func (c *credentialCoordinator) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供当前账号的窄凭证查询端口。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return credentialStateFingerprint(cookieStr, ""), nil
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 token 凭证一致性校验所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// runtimeData 已在调用方凭证锁内读取,避免校验期间混入另一笔 Cookie 更新。
|
||||
// Cookie 与 metadata 均由 repository 按账号作用域解密,登录密码不会进入此流程。
|
||||
// 后续空值判断、指纹比较和错误文案保持原有 token 绑定语义。
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
_, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete {
|
||||
return "", fmt.Errorf("数据库 Cookie 为空且没有权威 Jar")
|
||||
}
|
||||
if credentialCookieFingerprint(runtimeData.Value) != credentialCookieFingerprint(cookieStr) {
|
||||
return "", fmt.Errorf("token 请求期间数据库 Cookie 已变化")
|
||||
}
|
||||
return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON), nil
|
||||
}
|
||||
|
||||
// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存。普通 Cookie
|
||||
// 更新不轮换页面生命周期内的 device ID;显式登录由 Manager 重建 Account。
|
||||
// reloadCookieFromDB 封装reload登录凭证FromDB业务协调。
|
||||
func (c *credentialCoordinator) reloadCookieFromDB(ctx context.Context) bool {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供运行时状态与 Cookie repository。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return false
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含检测外部凭证更新所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(runtimeData.Value) == "" {
|
||||
if // complete 用于本次流程后续判断的complete
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// databaseFP 用于本次流程后续判断的databaseFP
|
||||
databaseFP := credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON)
|
||||
a.mu.Lock()
|
||||
// currentFP 用于本次流程后续判断的currentFP
|
||||
currentFP := a.credentialFP
|
||||
if currentFP == "" {
|
||||
currentFP = credentialStateFingerprint(a.CookieStr, "")
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if databaseFP == currentFP {
|
||||
return false
|
||||
}
|
||||
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
|
||||
a.replaceCredentialState(runtimeData.Value, databaseFP)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.mu.Lock()
|
||||
a.lastCaptchaFailure = time.Time{}
|
||||
a.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
// cookieSnapshotMatchesDB 封装登录凭证SnapshotMatchesDB业务协调。
|
||||
func (c *credentialCoordinator) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 WS 注册前的窄凭证查询端口。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return true
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 WS 注册前凭证一致性校验所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
a.logger.Warn("WS 注册前读取最新 Cookie 失败,放弃本次连接", "err", err)
|
||||
return false
|
||||
}
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
_, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete {
|
||||
a.logger.Warn("WS 注册前最新 Cookie 为空且没有权威 Jar,放弃本次连接")
|
||||
return false
|
||||
}
|
||||
if expectedFP == "" {
|
||||
a.logger.Warn("WS 注册 token 缺少绑定的凭证状态,放弃本次连接")
|
||||
return false
|
||||
}
|
||||
return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) == expectedFP
|
||||
}
|
||||
|
||||
// replaceCookieStr 封装replace登录凭证Str业务协调。
|
||||
func (c *credentialCoordinator) replaceCookieStr(cookieStr string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有运行时 Cookie 状态。
|
||||
a := c.account
|
||||
a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, ""))
|
||||
}
|
||||
|
||||
// replaceCredentialState 封装replaceCredential状态业务协调。
|
||||
func (c *credentialCoordinator) replaceCredentialState(cookieStr, credentialFP string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有凭证状态锁与用户身份快照。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.CookieStr = cookieStr
|
||||
a.credentialFP = credentialFP
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
|
||||
a.UserID = unb
|
||||
}
|
||||
}
|
||||
|
||||
// updateCookie 用外部刷新得到的新 Cookie 更新运行时状态,并在调用方 Context 到期时停止等待。
|
||||
func (c *credentialCoordinator) updateCookie(ctx context.Context, cookieStr string) error {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供权威 Cookie repository 与刷新门。
|
||||
a := c.account
|
||||
if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) {
|
||||
return nil
|
||||
}
|
||||
// releaseRefreshGate 释放运行时 Cookie 同步占用的通道令牌。
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx)
|
||||
if gateErr != nil {
|
||||
return fmt.Errorf("获取运行时 Cookie 同步门: %w", gateErr)
|
||||
}
|
||||
defer releaseRefreshGate()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
}
|
||||
defer credentialUnlock()
|
||||
// 外部调用通常发生在一次网络请求写回之后。调用排队期间可能已有更新的
|
||||
// Cookie 落库,因此参数只作为无 Store 场景的兼容值;有 Store 时始终
|
||||
// 复读权威数据库,绝不把较旧的请求结果重新写回运行时。
|
||||
// metadataJSON 用于本次流程后续判断的metadataJSON
|
||||
metadataJSON := ""
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// runtimeData、err 分别是账号运行时的权威 Cookie 快照及读取失败;查询继承调用方取消。
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取运行时 Cookie: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(runtimeData.Value) == "" {
|
||||
if // complete 用于本次流程后续判断的complete
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete {
|
||||
return errors.New("同步运行时 Cookie 时数据库值为空且无权威 Jar")
|
||||
}
|
||||
}
|
||||
cookieStr = runtimeData.Value
|
||||
metadataJSON = runtimeData.MetadataJSON
|
||||
}
|
||||
// credentialFP 用于本次流程后续判断的credentialFP
|
||||
credentialFP := credentialStateFingerprint(cookieStr, metadataJSON)
|
||||
a.mu.Lock()
|
||||
// changed 用于本次流程后续判断的changed
|
||||
changed := credentialFP != a.credentialFP
|
||||
a.mu.Unlock()
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
a.replaceCredentialState(cookieStr, credentialFP)
|
||||
// Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
|
||||
// 会在下一次自然重连前被重新读取并用于获取新的 accessToken。
|
||||
a.clearTokenCache(ctx)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// refreshToken 按账号凭证协调器的最小间隔规则刷新平台连接 Token,并返回 Token 与 Cookie 快照。
|
||||
func (c *credentialCoordinator) refreshToken(ctx context.Context) (string, string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,保留连接流程使用的返回契约。
|
||||
a := c.account
|
||||
return a.refreshTokenWithMinGap(ctx, false)
|
||||
}
|
||||
|
||||
// refreshTokenWithMinGap 保留旧签名以避免影响调用方;参考实现没有额外的一分钟
|
||||
// Token 防抖,因此 enforceMinGap 不参与行为。
|
||||
// refreshTokenWithMinGap 封装refresh令牌WithMinGap业务协调。
|
||||
func (c *credentialCoordinator) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,集中访问 MTOP、Cookie repository 和状态。
|
||||
a := c.account
|
||||
// releaseRefreshGate 释放 Token 刷新占用的通道令牌。
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx)
|
||||
if gateErr != nil {
|
||||
return "", "", gateErr
|
||||
}
|
||||
defer releaseRefreshGate()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := func() {}
|
||||
// credentialLocked 标识当前调用是否持有账号凭证锁。
|
||||
credentialLocked := false
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
}
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// refreshGate 串行化完整 Token/Cookie 更新事务;风控失败冷却仍由调用方状态控制。
|
||||
if // remaining 用于本次流程后续判断的remaining
|
||||
remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 {
|
||||
a.setLastTokenStatus(tokenRefreshSkippedCooldown)
|
||||
return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second))
|
||||
}
|
||||
|
||||
a.reloadCookieFromDB(ctx)
|
||||
|
||||
a.mu.Lock()
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := a.CookieStr
|
||||
// metadataJSON 保存当前凭证快照对应的 metadata。
|
||||
metadataJSON := ""
|
||||
a.lastTokenRefresh = time.Now()
|
||||
a.lastTokenStatus = tokenRefreshStarted
|
||||
a.mu.Unlock()
|
||||
|
||||
// deviceID 用于本次流程后续判断的deviceID
|
||||
deviceID := strings.TrimSpace(a.deviceID)
|
||||
if deviceID == "" {
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
|
||||
deviceID = protocol.GenerateDeviceID(unb)
|
||||
a.mu.Lock()
|
||||
a.deviceID = deviceID
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// runtimeData 保存 Token 请求开始前的最小凭证快照。
|
||||
runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if detailErr != nil {
|
||||
return "", "", detailErr
|
||||
}
|
||||
cookieStr = runtimeData.Value
|
||||
metadataJSON = runtimeData.MetadataJSON
|
||||
}
|
||||
// Token 网络请求和风控恢复都必须在共享凭证锁外执行。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
for // captchaRetry 用于本次流程后续判断的captcha重试
|
||||
captchaRetry := 0; captchaRetry < 3; captchaRetry++ {
|
||||
// res、err 保存本轮平台 Token 请求结果及其传输或业务失败原因。
|
||||
res, err := c.requestPlatformToken(ctx, cookieStr, deviceID)
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// credentialUnlock 保存 Token 响应提交临界区的释放函数。
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
// latestRuntimeData 和 reloadErr 保存网络请求完成后的最新凭证视图及重读错误。
|
||||
latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if reloadErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
return "", "", reloadErr
|
||||
}
|
||||
if latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON {
|
||||
// 并发流程已经更新凭证,丢弃旧请求的 Token 和 Cookie 响应,下一轮使用最新快照重试。
|
||||
cookieStr = latestRuntimeData.Value
|
||||
metadataJSON = latestRuntimeData.MetadataJSON
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
continue
|
||||
}
|
||||
}
|
||||
// 参考实现无论业务结果为何,都先合并响应 Set-Cookie。本地还必须先把
|
||||
// 完整 Jar 持久化成功,避免当前 /reg 成功而下次重连回滚到旧凭证。
|
||||
// 响应处理会广播给 Handler,因此先释放凭证锁,成功 Token 绑定前会重新校验。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
// persistErr 用于本次流程后续判断的persistErr
|
||||
var persistErr error
|
||||
cookieStr, persistErr = a.adoptTokenResponseCookies(ctx, cookieStr, res)
|
||||
if persistErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
return "", "", fmt.Errorf("保存 token 响应 Cookie: %w", persistErr)
|
||||
}
|
||||
if err != nil && mtop.IsRiskVerificationErr(err) {
|
||||
// 风控恢复是外部调用,不能在共享凭证锁内执行。
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
}
|
||||
if // recovered、ok 用于本次流程后续判断的recovered、ok
|
||||
recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, err); ok {
|
||||
cookieStr = recovered.UpdatedCookies
|
||||
// 重取地址时即使拿到了 accessToken,参考实现也不会直接采用;
|
||||
// 它会清缓存后重新走一次标准 token 请求。
|
||||
continue
|
||||
}
|
||||
a.markTokenCaptchaFailure()
|
||||
a.setLastTokenStatus(tokenRefreshFailedCaptcha)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", err
|
||||
}
|
||||
if err != nil {
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := classifyTokenFailure(err)
|
||||
a.setLastTokenStatus(status)
|
||||
a.clearCurrentToken()
|
||||
if status != tokenRefreshFailedNetwork && status != tokenRefreshFailedTimeout {
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
if res == nil || strings.TrimSpace(res.AccessToken) == "" {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("token API 未返回结果")
|
||||
}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
credentialLocked = true
|
||||
}
|
||||
// credentialFP、fingerprintErr 用于本次流程后续判断的credentialFP、fingerprintErr
|
||||
credentialFP, fingerprintErr := a.databaseCredentialFingerprint(ctx, cookieStr)
|
||||
if fingerprintErr != nil {
|
||||
a.setLastTokenStatus(tokenRefreshFailedAPI)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("绑定 token 凭证状态: %w", fingerprintErr)
|
||||
}
|
||||
a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, credentialFP)
|
||||
a.mu.Lock()
|
||||
a.credentialFP = credentialFP
|
||||
a.tokenCredentialFP = credentialFP
|
||||
a.lastCaptchaFailure = time.Time{}
|
||||
a.tokenFetchFailures = 0
|
||||
a.lastTokenStatus = tokenRefreshSuccess
|
||||
a.mu.Unlock()
|
||||
a.runtimeMu.Lock()
|
||||
a.lastMsgReceived = time.Time{}
|
||||
a.runtimeMu.Unlock()
|
||||
return res.AccessToken, cookieStr, nil
|
||||
}
|
||||
|
||||
a.setLastTokenStatus(tokenRefreshFailedCaptcha)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
return "", "", fmt.Errorf("滑块验证重试次数已达上限")
|
||||
}
|
||||
|
||||
// requestPlatformToken 使用具备凭证快照能力的客户端请求 Token;旧客户端保持扁平 Cookie 兼容路径。
|
||||
func (c *credentialCoordinator) requestPlatformToken(ctx context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,保存平台客户端与凭证快照仓储。
|
||||
a := c.account
|
||||
// scoped、ok 分别是支持权威 Cookie 快照的 MTOP 客户端及其类型断言结果。
|
||||
if scoped, ok := a.mtop.(scopedTokenClient); ok {
|
||||
// snapshot 是当前 Cookie metadata 的权威快照;读取失败时退回客户端既有扁平凭证请求语义。
|
||||
var snapshot []cookierefresh.BrowserCookie
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// metadata、metadataErr 分别是账号 Cookie 快照元数据及其读取失败原因;读取失败时保持兼容请求路径。
|
||||
if metadata, metadataErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID); metadataErr == nil {
|
||||
snapshot = cookierefresh.SnapshotFromMetadata(metadata)
|
||||
}
|
||||
}
|
||||
return scoped.RefreshTokenWithCredentialContext(ctx, cookieStr, deviceID, snapshot)
|
||||
}
|
||||
return a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
|
||||
}
|
||||
|
||||
// clearCurrentToken 封装clearCurrent令牌业务协调。
|
||||
func (c *credentialCoordinator) clearCurrentToken() {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有 Token 状态锁。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.currentToken = ""
|
||||
a.tokenCredentialFP = ""
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// adoptTokenResponseCookies 封装adopt令牌响应Cookies业务协调。
|
||||
func (c *credentialCoordinator) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) (string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Cookie 持久化与回调端口。
|
||||
a := c.account
|
||||
if res == nil {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if !res.CookieSnapshotComplete && !res.CookieStateChanged && strings.TrimSpace(res.UpdatedCookies) == "" {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if !res.CookieSnapshotComplete && !res.CookieStateChanged && res.UpdatedCookies == cookieStr && len(res.CookieSnapshot) == 0 {
|
||||
return cookieStr, nil
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
metadata, detailErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含 token 响应 Cookie 合并所需的快照信息。
|
||||
if detailErr != nil {
|
||||
return cookieStr, detailErr
|
||||
}
|
||||
// metadata 已在 repository 层按账号作用域解密,不读取旧 Cookie 或登录秘密。
|
||||
// 下面继续根据响应类型合并已有快照,并由 UpdateRenewalCookie 统一持久化。
|
||||
// 错误返回和运行时状态更新顺序保持原有 token 响应语义。
|
||||
// 只有 token 响应本身发生变化时才进入后续快照合并逻辑。
|
||||
if res.CookieSnapshotComplete {
|
||||
// snapshot 用于本次流程后续判断的snapshot
|
||||
snapshot := cookierefresh.NormalizeSnapshot(res.CookieSnapshot)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
|
||||
} else if // snapshot、snapshotOK 用于本次流程后续判断的snapshot、snapshotOK
|
||||
snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(metadata); snapshotOK {
|
||||
// 扁平结果不能凭空证明 Jar 完整;仅在已有权威 Jar 时按已知
|
||||
// Domain/Path 身份对值做兼容合并。
|
||||
snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies)
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
|
||||
} else {
|
||||
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return cookieStr, err
|
||||
}
|
||||
a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata))
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
return res.UpdatedCookies, nil
|
||||
}
|
||||
if res.UpdatedCookies != cookieStr {
|
||||
a.replaceCookieStr(res.UpdatedCookies)
|
||||
}
|
||||
return res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
// tryTokenCaptchaRecovery 封装try令牌CaptchaRecovery业务协调。
|
||||
func (c *credentialCoordinator) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, err error) (*mtop.RefreshResult, bool) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供风控 Handler 与运行时状态。
|
||||
a := c.account
|
||||
// h、ok 用于本次流程后续判断的h、ok
|
||||
h, ok := a.handler.(tokenCaptchaHandler)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
// riskErr 用于本次流程后续判断的riskErr
|
||||
var riskErr *mtop.RiskVerificationError
|
||||
if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" {
|
||||
return nil, false
|
||||
}
|
||||
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证",
|
||||
"token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。")
|
||||
// result、ok 用于本次流程后续判断的result、ok
|
||||
result, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL, deviceID)
|
||||
if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
// updatedCookies、persistErr 用于本次流程后续判断的updatedCookies、persistErr
|
||||
updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result)
|
||||
if persistErr != nil {
|
||||
a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr)
|
||||
return nil, false
|
||||
}
|
||||
result.UpdatedCookies = updatedCookies
|
||||
a.replaceCookieStr(updatedCookies)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage)
|
||||
return result, true
|
||||
}
|
||||
|
||||
// markTokenCaptchaFailure 封装mark令牌CaptchaFailure业务协调。
|
||||
func (c *credentialCoordinator) markTokenCaptchaFailure() {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.lastCaptchaFailure = time.Now()
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// tokenCaptchaCooldownRemaining 封装令牌CaptchaCooldownRemaining业务协调。
|
||||
func (c *credentialCoordinator) tokenCaptchaCooldownRemaining() time.Duration {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
// lastFailure 用于本次流程后续判断的lastFailure
|
||||
lastFailure := a.lastCaptchaFailure
|
||||
a.mu.Unlock()
|
||||
if lastFailure.IsZero() {
|
||||
return 0
|
||||
}
|
||||
// remaining 用于本次流程后续判断的remaining
|
||||
remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure)
|
||||
if remaining < 0 {
|
||||
return 0
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
|
||||
// saveTokenCache records the server expiry and current page-runtime identity.
|
||||
// It is diagnostic state only: acquireToken never reads the accessToken back
|
||||
// for a later WebSocket registration.
|
||||
// saveTokenCache 封装save令牌Cache业务协调。
|
||||
func (c *credentialCoordinator) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Token repository 与诊断日志。
|
||||
a := c.account
|
||||
if accessToken == "" {
|
||||
return
|
||||
}
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now()
|
||||
// expiresAt、refreshAt 用于本次流程后续判断的expiresAt、refreshAt
|
||||
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
|
||||
// tokenFP 用于本次流程后续判断的令牌FP
|
||||
tokenFP := tokenFingerprint(accessToken)
|
||||
a.mu.Lock()
|
||||
// previousTokenFP 用于本次流程后续判断的previous令牌FP
|
||||
previousTokenFP := a.tokenFingerprint
|
||||
a.tokenFingerprint = tokenFP
|
||||
a.tokenAcquiredAt = now
|
||||
a.tokenExpiresAt = expiresAt
|
||||
a.tokenRefreshAt = refreshAt
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP)
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
// expireAt 用于本次流程后续判断的expireAt
|
||||
expireAt := effectiveTokenExpireAt(serverExpireAt, now)
|
||||
if expireAt == 0 {
|
||||
// 服务端未给有效期时仍使用保守运行时轮换时间,但不把推测期限
|
||||
// 伪装成服务端缓存期限。
|
||||
a.logger.Warn("token API 未返回可用过期时间,使用保守轮换时间", "refresh_at", refreshAt)
|
||||
a.clearTokenCache(ctx)
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialFP); err != nil {
|
||||
a.logger.Warn("缓存 accessToken 失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token,
|
||||
// 同时避免日志泄露可用于 WS 注册的凭证原文。
|
||||
// tokenFingerprint 封装令牌Fingerprint业务协调。
|
||||
func tokenFingerprint(token string) string {
|
||||
// sum 用于本次流程后续判断的sum
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return fmt.Sprintf("%x", sum[:6])
|
||||
}
|
||||
|
||||
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
|
||||
func (c *credentialCoordinator) clearTokenCache(ctx context.Context) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 Token repository 与内存状态。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
a.tokenFingerprint = ""
|
||||
a.mu.Unlock()
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := a.store.Tokens.Clear(ctx, a.CookieID); err != nil {
|
||||
a.logger.Warn("清除 token 缓存失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// databaseCredentialFingerprint returns the complete DB credential state that
|
||||
// produced cookieStr. It must be called while the account credential lock is
|
||||
// held when a Store is present.
|
||||
// databaseCredentialFingerprint 封装databaseCredentialFingerprint业务协调。
|
||||
func (c *credentialCoordinator) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供当前账号的窄凭证查询端口。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return credentialStateFingerprint(cookieStr, ""), nil
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 token 凭证一致性校验所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// runtimeData 已在调用方凭证锁内读取,避免校验期间混入另一笔 Cookie 更新。
|
||||
// Cookie 与 metadata 均由 repository 按账号作用域解密,登录密码不会进入此流程。
|
||||
// 后续空值判断、指纹比较和错误文案保持原有 token 绑定语义。
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
_, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete {
|
||||
return "", fmt.Errorf("数据库 Cookie 为空且没有权威 Jar")
|
||||
}
|
||||
if credentialCookieFingerprint(runtimeData.Value) != credentialCookieFingerprint(cookieStr) {
|
||||
return "", fmt.Errorf("token 请求期间数据库 Cookie 已变化")
|
||||
}
|
||||
return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON), nil
|
||||
}
|
||||
|
||||
// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存。普通 Cookie
|
||||
// 更新不轮换页面生命周期内的 device ID;显式登录由 Manager 重建 Account。
|
||||
// reloadCookieFromDB 封装reload登录凭证FromDB业务协调。
|
||||
func (c *credentialCoordinator) reloadCookieFromDB(ctx context.Context) bool {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供运行时状态与 Cookie repository。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return false
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含检测外部凭证更新所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(runtimeData.Value) == "" {
|
||||
if // complete 用于本次流程后续判断的complete
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// databaseFP 用于本次流程后续判断的databaseFP
|
||||
databaseFP := credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON)
|
||||
a.mu.Lock()
|
||||
// currentFP 用于本次流程后续判断的currentFP
|
||||
currentFP := a.credentialFP
|
||||
if currentFP == "" {
|
||||
currentFP = credentialStateFingerprint(a.CookieStr, "")
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if databaseFP == currentFP {
|
||||
return false
|
||||
}
|
||||
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
|
||||
a.replaceCredentialState(runtimeData.Value, databaseFP)
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.mu.Lock()
|
||||
a.lastCaptchaFailure = time.Time{}
|
||||
a.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
// cookieSnapshotMatchesDB 封装登录凭证SnapshotMatchesDB业务协调。
|
||||
func (c *credentialCoordinator) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供 WS 注册前的窄凭证查询端口。
|
||||
a := c.account
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return true
|
||||
}
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 WS 注册前凭证一致性校验所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
a.logger.Warn("WS 注册前读取最新 Cookie 失败,放弃本次连接", "err", err)
|
||||
return false
|
||||
}
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
_, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete {
|
||||
a.logger.Warn("WS 注册前最新 Cookie 为空且没有权威 Jar,放弃本次连接")
|
||||
return false
|
||||
}
|
||||
if expectedFP == "" {
|
||||
a.logger.Warn("WS 注册 token 缺少绑定的凭证状态,放弃本次连接")
|
||||
return false
|
||||
}
|
||||
return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) == expectedFP
|
||||
}
|
||||
|
||||
// replaceCookieStr 封装replace登录凭证Str业务协调。
|
||||
func (c *credentialCoordinator) replaceCookieStr(cookieStr string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有运行时 Cookie 状态。
|
||||
a := c.account
|
||||
a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, ""))
|
||||
}
|
||||
|
||||
// replaceCredentialState 封装replaceCredential状态业务协调。
|
||||
func (c *credentialCoordinator) replaceCredentialState(cookieStr, credentialFP string) {
|
||||
// a 是本凭证协调器绑定的账号 facade,持有凭证状态锁与用户身份快照。
|
||||
a := c.account
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.CookieStr = cookieStr
|
||||
a.credentialFP = credentialFP
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
|
||||
a.UserID = unb
|
||||
}
|
||||
}
|
||||
|
||||
// updateCookie 用外部刷新得到的新 Cookie 更新运行时状态,并在调用方 Context 到期时停止等待。
|
||||
func (c *credentialCoordinator) updateCookie(ctx context.Context, cookieStr string) error {
|
||||
// a 是本凭证协调器绑定的账号 facade,提供权威 Cookie repository 与刷新门。
|
||||
a := c.account
|
||||
if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) {
|
||||
return nil
|
||||
}
|
||||
// releaseRefreshGate 释放运行时 Cookie 同步占用的通道令牌。
|
||||
releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx)
|
||||
if gateErr != nil {
|
||||
return fmt.Errorf("获取运行时 Cookie 同步门: %w", gateErr)
|
||||
}
|
||||
defer releaseRefreshGate()
|
||||
// credentialUnlock 用于本次流程后续判断的credentialUnlock
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
}
|
||||
defer credentialUnlock()
|
||||
// 外部调用通常发生在一次网络请求写回之后。调用排队期间可能已有更新的
|
||||
// Cookie 落库,因此参数只作为无 Store 场景的兼容值;有 Store 时始终
|
||||
// 复读权威数据库,绝不把较旧的请求结果重新写回运行时。
|
||||
// metadataJSON 用于本次流程后续判断的metadataJSON
|
||||
metadataJSON := ""
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
// runtimeData、err 分别是账号运行时的权威 Cookie 快照及读取失败;查询继承调用方取消。
|
||||
runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取运行时 Cookie: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(runtimeData.Value) == "" {
|
||||
if // complete 用于本次流程后续判断的complete
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete {
|
||||
return errors.New("同步运行时 Cookie 时数据库值为空且无权威 Jar")
|
||||
}
|
||||
}
|
||||
cookieStr = runtimeData.Value
|
||||
metadataJSON = runtimeData.MetadataJSON
|
||||
}
|
||||
// credentialFP 用于本次流程后续判断的credentialFP
|
||||
credentialFP := credentialStateFingerprint(cookieStr, metadataJSON)
|
||||
a.mu.Lock()
|
||||
// changed 用于本次流程后续判断的changed
|
||||
changed := credentialFP != a.credentialFP
|
||||
a.mu.Unlock()
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
a.replaceCredentialState(cookieStr, credentialFP)
|
||||
// Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
|
||||
// 会在下一次自然重连前被重新读取并用于获取新的 accessToken。
|
||||
a.clearTokenCache(ctx)
|
||||
return nil
|
||||
}
|
||||
@@ -4,25 +4,14 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -570,568 +559,3 @@ func sortStrings(values []string) {
|
||||
}
|
||||
|
||||
// send 封装send业务协调。
|
||||
func (n *Notifier) send(ch db.NotificationChannel, message string) error {
|
||||
// cfg 用于本次流程后续判断的cfg
|
||||
cfg := parseConfig(ch.Config)
|
||||
switch ch.Type {
|
||||
case "ding_talk", "dingtalk":
|
||||
return n.sendDingTalk(cfg, message)
|
||||
case "feishu", "lark":
|
||||
return n.sendFeishu(cfg, message)
|
||||
case "bark":
|
||||
return n.sendBark(cfg, message)
|
||||
case "webhook":
|
||||
return n.sendWebhook(cfg, message)
|
||||
case "wechat":
|
||||
return n.sendWeChat(cfg, message)
|
||||
case "telegram":
|
||||
return n.sendTelegram(cfg, message)
|
||||
case "email":
|
||||
return n.sendEmail(cfg, message)
|
||||
case "qq":
|
||||
// QQ 渠道配置未标准化,跳过。
|
||||
return fmt.Errorf("qq 渠道暂不支持")
|
||||
default:
|
||||
return fmt.Errorf("不支持的通知渠道类型: %s", ch.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// parseConfig 解析 config JSON,失败时兼容旧格式 {"config": <raw>}。
|
||||
func parseConfig(config string) map[string]any {
|
||||
if config == "" {
|
||||
return map[string]any{}
|
||||
}
|
||||
// m 用于本次流程后续判断的m
|
||||
var m map[string]any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(config), &m); err != nil {
|
||||
return map[string]any{"config": config}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ---- 钉钉 ----
|
||||
func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", strOr(cfg, "config", ""))
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("钉钉 webhook_url 为空")
|
||||
}
|
||||
if secret != "" {
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(secret))
|
||||
h.Write([]byte(stringToSign))
|
||||
// sign 用于本次流程后续判断的sign
|
||||
sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
// parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := url.Parse(webhook)
|
||||
if err != nil {
|
||||
return fmt.Errorf("钉钉 webhook 地址无效: %w", err)
|
||||
}
|
||||
// query 用于本次流程后续判断的查询
|
||||
query := parsed.Query()
|
||||
query.Set("timestamp", ts)
|
||||
query.Set("sign", sign)
|
||||
parsed.RawQuery = query.Encode()
|
||||
webhook = parsed.String()
|
||||
}
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
payload := map[string]any{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]any{
|
||||
"title": "闲鱼自动回复通知",
|
||||
"text": message,
|
||||
},
|
||||
}
|
||||
return n.postJSON(webhook, payload)
|
||||
}
|
||||
|
||||
// ---- 飞书 ----
|
||||
func (n *Notifier) sendFeishu(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("飞书 webhook_url 为空")
|
||||
}
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"msg_type": "text",
|
||||
"content": map[string]any{"text": message},
|
||||
"timestamp": ts,
|
||||
}
|
||||
if secret != "" {
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
h.Write([]byte(""))
|
||||
data["sign"] = base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
return n.postJSON(webhook, data)
|
||||
}
|
||||
|
||||
// ---- Bark ----
|
||||
// sendBark 封装sendBark业务协调。
|
||||
func (n *Notifier) sendBark(cfg map[string]any, message string) error {
|
||||
// server 用于本次流程后续判断的server
|
||||
server := strings.TrimRight(strOr(cfg, "server_url", "https://api.day.app"), "/")
|
||||
// deviceKey 用于本次流程后续判断的deviceKey
|
||||
deviceKey := strOr(cfg, "device_key", "")
|
||||
if deviceKey == "" {
|
||||
return fmt.Errorf("bark device_key 为空")
|
||||
}
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"device_key": deviceKey,
|
||||
"title": strOr(cfg, "title", "闲鱼自动回复通知"),
|
||||
"body": message,
|
||||
"sound": strOr(cfg, "sound", "default"),
|
||||
"group": strOr(cfg, "group", "xianyu"),
|
||||
}
|
||||
if // icon 用于本次流程后续判断的icon
|
||||
icon := strOr(cfg, "icon", ""); icon != "" {
|
||||
data["icon"] = icon
|
||||
}
|
||||
if // u 用于本次流程后续判断的u
|
||||
u := strOr(cfg, "url", ""); u != "" {
|
||||
data["url"] = u
|
||||
}
|
||||
return n.postJSON(server+"/push", data)
|
||||
}
|
||||
|
||||
// ---- Webhook ----
|
||||
// sendWebhook 封装sendWebhook业务协调。
|
||||
func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("webhook_url 为空")
|
||||
}
|
||||
// method 用于本次流程后续判断的方法
|
||||
method := strings.ToUpper(strOr(cfg, "http_method", "POST"))
|
||||
// headers 用于本次流程后续判断的headers
|
||||
headers := map[string]any{}
|
||||
if // h 用于本次流程后续判断的h
|
||||
h := strOr(cfg, "headers", ""); h != "" {
|
||||
_ = json.Unmarshal([]byte(h), &headers)
|
||||
}
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"message": message,
|
||||
"timestamp": time.Now().Format("2006-01-02 15:04:05"),
|
||||
"source": "xianyu-auto-reply",
|
||||
}
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := json.Marshal(data)
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequest(method, webhook, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("webhook 状态码 %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- 企业微信 ----
|
||||
func (n *Notifier) sendWeChat(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("微信 webhook_url 为空")
|
||||
}
|
||||
return n.postJSON(webhook, map[string]any{
|
||||
"msgtype": "text",
|
||||
"text": map[string]any{"content": message},
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Telegram ----
|
||||
// sendTelegram 封装sendTelegram业务协调。
|
||||
func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
// botToken 用于本次流程后续判断的bot令牌
|
||||
botToken := strOr(cfg, "bot_token", "")
|
||||
// chatID 用于本次流程后续判断的聊天ID
|
||||
chatID := strOr(cfg, "chat_id", "")
|
||||
if botToken == "" || chatID == "" {
|
||||
return fmt.Errorf("telegram bot_token/chat_id 不完整")
|
||||
}
|
||||
// endpoint 用于本次流程后续判断的endpoint
|
||||
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
return n.postJSON(endpoint, map[string]any{
|
||||
"chat_id": chatID,
|
||||
"text": message,
|
||||
})
|
||||
}
|
||||
|
||||
// ---- 邮件 ----
|
||||
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
// server 用于本次流程后续判断的server
|
||||
server := n.smtpConfigValue(ctx, cfg, "smtp_server", "")
|
||||
// port 用于本次流程后续判断的port
|
||||
port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587")
|
||||
// user 用于本次流程后续判断的用户
|
||||
user := n.smtpConfigValue(ctx, cfg, "smtp_user", "")
|
||||
// pass 用于本次流程后续判断的pass
|
||||
pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "")
|
||||
// useTLS 用于本次流程后续判断的useTLS
|
||||
useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true)
|
||||
// useSSL 用于本次流程后续判断的useSSL
|
||||
useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false)
|
||||
// fromAddress 用于本次流程后续判断的fromAddress
|
||||
fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "")
|
||||
// fromName 用于本次流程后续判断的from名称
|
||||
fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "")
|
||||
// legacyFrom 用于本次流程后续判断的legacyFrom
|
||||
legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "")
|
||||
// to 用于本次流程后续判断的to
|
||||
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
|
||||
if server == "" || user == "" || to == "" {
|
||||
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
|
||||
}
|
||||
if legacyFrom != "" {
|
||||
if // parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := mail.ParseAddress(legacyFrom); err == nil && strings.Contains(parsed.Address, "@") {
|
||||
if fromAddress == "" {
|
||||
fromAddress = parsed.Address
|
||||
}
|
||||
if fromName == "" {
|
||||
fromName = parsed.Name
|
||||
}
|
||||
} else if fromName == "" {
|
||||
fromName = legacyFrom
|
||||
}
|
||||
}
|
||||
if fromAddress == "" {
|
||||
fromAddress = user
|
||||
}
|
||||
// from、err 用于本次流程后续判断的from、err
|
||||
from, err := mail.ParseAddress(fromAddress)
|
||||
if err != nil || !strings.Contains(from.Address, "@") {
|
||||
return fmt.Errorf("发件邮箱地址无效")
|
||||
}
|
||||
// recipient、err 用于本次流程后续判断的recipient、err
|
||||
recipient, err := mail.ParseAddress(to)
|
||||
if err != nil || !strings.Contains(recipient.Address, "@") {
|
||||
return fmt.Errorf("收件邮箱地址无效")
|
||||
}
|
||||
from.Name = fromName
|
||||
// fromHeader 用于本次流程后续判断的fromHeader
|
||||
fromHeader := from.Address
|
||||
if from.Name != "" {
|
||||
fromHeader = from.String()
|
||||
}
|
||||
// toHeader 用于本次流程后续判断的toHeader
|
||||
toHeader := recipient.Address
|
||||
if recipient.Name != "" {
|
||||
toHeader = recipient.String()
|
||||
}
|
||||
// addr 用于本次流程后续判断的addr
|
||||
addr := server + ":" + port
|
||||
// auth 用于本次流程后续判断的auth
|
||||
auth := smtp.PlainAuth("", user, pass, server)
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.Join([]string{
|
||||
"From: " + fromHeader,
|
||||
"To: " + toHeader,
|
||||
"Subject: =?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte("闲鱼自动发货通知")) + "?=",
|
||||
"MIME-Version: 1.0",
|
||||
"Content-Type: text/plain; charset=UTF-8",
|
||||
"",
|
||||
message,
|
||||
}, "\r\n")
|
||||
return sendPublicSMTP(ctx, addr, server, auth, from.Address, recipient.Address, []byte(msg), smtpTransportOptions{
|
||||
UseSTARTTLS: useTLS && !useSSL,
|
||||
UseImplicitTLS: useSSL,
|
||||
})
|
||||
}
|
||||
|
||||
// smtpTransportOptions 用于本次流程后续判断的smtpTransportOptions
|
||||
type smtpTransportOptions struct {
|
||||
UseSTARTTLS bool
|
||||
UseImplicitTLS bool
|
||||
}
|
||||
|
||||
// sendPublicSMTP 封装sendPublicSMTP业务协调。
|
||||
func sendPublicSMTP(ctx context.Context, addr, server string, auth smtp.Auth, from, to string, message []byte, options ...smtpTransportOptions) error {
|
||||
// rawPort、err 用于本次流程后续判断的原始Port、err
|
||||
_, rawPort, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 地址无效")
|
||||
}
|
||||
// port、err 用于本次流程后续判断的port、err
|
||||
port, err := strconv.Atoi(strings.TrimSpace(rawPort))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return fmt.Errorf("SMTP 端口无效")
|
||||
}
|
||||
// conn、err 用于本次流程后续判断的conn、err
|
||||
conn, err := dialPublicSMTP(ctx, "tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接 SMTP 服务器失败: %w", err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
_ = conn.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
// transport 用于本次流程后续判断的transport
|
||||
transport := smtpTransportOptions{UseSTARTTLS: true}
|
||||
if len(options) > 0 {
|
||||
transport = options[0]
|
||||
}
|
||||
if transport.UseImplicitTLS {
|
||||
// tlsConn 用于本次流程后续判断的tlsConn
|
||||
tlsConn := tls.Client(conn, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: server})
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return fmt.Errorf("SMTP SSL 握手失败: %w", err)
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
// client、err 用于本次流程后续判断的client、err
|
||||
client, err := smtp.NewClient(conn, server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
if transport.UseSTARTTLS {
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
ok, _ := client.Extension("STARTTLS"); !ok {
|
||||
return fmt.Errorf("SMTP 服务器不支持要求的 STARTTLS")
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: server}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if auth != nil {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Auth(auth); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
// w、err 用于本次流程后续判断的w、err
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := w.Write(message); err != nil {
|
||||
_ = w.Close()
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
// parseConfigBool 封装parse配置Bool业务协调。
|
||||
func parseConfigBool(raw string, fallback bool) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
case "0", "false", "no", "off":
|
||||
return false
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
// configOrSetting 封装配置Or设置业务协调。
|
||||
func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
if // v 用于本次流程后续判断的v
|
||||
v := strings.TrimSpace(strOr(cfg, key, "")); v != "" {
|
||||
return v
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // v、err 用于本次流程后续判断的v、err
|
||||
v, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// smtpConfigValue keeps legacy per-field fallback behavior for existing rows,
|
||||
// while new rows use an explicit all-system or all-channel SMTP mode.
|
||||
// smtpConfigValue 封装smtp配置值业务协调。
|
||||
func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
// modeValue、hasExplicitMode 用于本次流程后续判断的模式Value、hasExplicit模式
|
||||
modeValue, hasExplicitMode := cfg["use_custom_smtp"]
|
||||
if !hasExplicitMode {
|
||||
return n.configOrSetting(ctx, cfg, key, fallbackValue)
|
||||
}
|
||||
if parseConfigBool(fmt.Sprintf("%v", modeValue), false) {
|
||||
if // value 用于本次流程后续判断的值
|
||||
value := strings.TrimSpace(strOr(cfg, key, "")); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // value、err 用于本次流程后续判断的value、err
|
||||
value, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// postJSON 通用 JSON POST。
|
||||
func (n *Notifier) postJSON(url string, payload any) error {
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// requestCtx、requestCancel 为单次渠道 HTTP 请求创建有界取消路径。
|
||||
requestCtx, requestCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer requestCancel()
|
||||
// req、err 分别是携带取消语义的渠道 HTTP 请求及其构造错误。
|
||||
req, err := http.NewRequestWithContext(requestCtx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// responseBody、err 用于本次流程后续判断的响应Body、err
|
||||
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("状态码 %d", resp.StatusCode)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := notificationBusinessError(responseBody); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notificationBusinessError 封装通知Business错误业务协调。
|
||||
func notificationBusinessError(body []byte) error {
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return nil
|
||||
}
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) != nil {
|
||||
return nil
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := strings.TrimSpace(firstMapString(payload, "errmsg", "msg", "message", "description"))
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "errcode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "StatusCode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "code"); ok && code != 0 && code != 200 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // okValue、exists 用于本次流程后续判断的okValue、exists
|
||||
okValue, exists := payload["ok"].(bool); exists && !okValue {
|
||||
return fmt.Errorf("通知渠道返回失败: %s", message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapNumber 封装mapNumber业务协调。
|
||||
func mapNumber(payload map[string]any, key string) (float64, bool) {
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
switch // typed 用于本次流程后续判断的typed
|
||||
typed := value.(type) {
|
||||
case float64:
|
||||
return typed, true
|
||||
case string:
|
||||
// number、err 用于本次流程后续判断的number、err
|
||||
number, err := strconv.ParseFloat(typed, 64)
|
||||
return number, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// firstMapString 封装firstMapString业务协调。
|
||||
func firstMapString(payload map[string]any, keys ...string) string {
|
||||
// key 表示当前遍历过程中的key
|
||||
for _, key := range keys {
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key].(string); ok && value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return "未知错误"
|
||||
}
|
||||
|
||||
// strOr 从 map 取字符串,缺失返回 fallback。
|
||||
func strOr(m map[string]any, key, fallback string) string {
|
||||
if // v、ok 用于本次流程后续判断的v、ok
|
||||
v, ok := m[key]; ok {
|
||||
switch // x 用于本次流程后续判断的x
|
||||
x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
default:
|
||||
return fmt.Sprintf("%v", x)
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// fallback 封装fallback业务协调。
|
||||
func fallback(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// send 根据渠道类型将已格式化通知发送到外部服务;渠道配置错误直接返回供 outbox 重试分类。
|
||||
func (n *Notifier) send(ch db.NotificationChannel, message string) error {
|
||||
// cfg 用于本次流程后续判断的cfg
|
||||
cfg := parseConfig(ch.Config)
|
||||
switch ch.Type {
|
||||
case "ding_talk", "dingtalk":
|
||||
return n.sendDingTalk(cfg, message)
|
||||
case "feishu", "lark":
|
||||
return n.sendFeishu(cfg, message)
|
||||
case "bark":
|
||||
return n.sendBark(cfg, message)
|
||||
case "webhook":
|
||||
return n.sendWebhook(cfg, message)
|
||||
case "wechat":
|
||||
return n.sendWeChat(cfg, message)
|
||||
case "telegram":
|
||||
return n.sendTelegram(cfg, message)
|
||||
case "email":
|
||||
return n.sendEmail(cfg, message)
|
||||
case "qq":
|
||||
// QQ 渠道配置未标准化,跳过。
|
||||
return fmt.Errorf("qq 渠道暂不支持")
|
||||
default:
|
||||
return fmt.Errorf("不支持的通知渠道类型: %s", ch.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// parseConfig 解析 config JSON,失败时兼容旧格式 {"config": <raw>}。
|
||||
func parseConfig(config string) map[string]any {
|
||||
if config == "" {
|
||||
return map[string]any{}
|
||||
}
|
||||
// m 用于本次流程后续判断的m
|
||||
var m map[string]any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(config), &m); err != nil {
|
||||
return map[string]any{"config": config}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ---- 钉钉 ----
|
||||
func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", strOr(cfg, "config", ""))
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("钉钉 webhook_url 为空")
|
||||
}
|
||||
if secret != "" {
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(secret))
|
||||
h.Write([]byte(stringToSign))
|
||||
// sign 用于本次流程后续判断的sign
|
||||
sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
// parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := url.Parse(webhook)
|
||||
if err != nil {
|
||||
return fmt.Errorf("钉钉 webhook 地址无效: %w", err)
|
||||
}
|
||||
// query 用于本次流程后续判断的查询
|
||||
query := parsed.Query()
|
||||
query.Set("timestamp", ts)
|
||||
query.Set("sign", sign)
|
||||
parsed.RawQuery = query.Encode()
|
||||
webhook = parsed.String()
|
||||
}
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
payload := map[string]any{
|
||||
"msgtype": "markdown",
|
||||
"markdown": map[string]any{
|
||||
"title": "闲鱼自动回复通知",
|
||||
"text": message,
|
||||
},
|
||||
}
|
||||
return n.postJSON(webhook, payload)
|
||||
}
|
||||
|
||||
// ---- 飞书 ----
|
||||
func (n *Notifier) sendFeishu(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
// secret 用于本次流程后续判断的secret
|
||||
secret := strOr(cfg, "secret", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("飞书 webhook_url 为空")
|
||||
}
|
||||
// ts 用于本次流程后续判断的ts
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"msg_type": "text",
|
||||
"content": map[string]any{"text": message},
|
||||
"timestamp": ts,
|
||||
}
|
||||
if secret != "" {
|
||||
// stringToSign 用于本次流程后续判断的stringToSign
|
||||
stringToSign := ts + "\n" + secret
|
||||
// h 用于本次流程后续判断的h
|
||||
h := hmac.New(sha256.New, []byte(stringToSign))
|
||||
h.Write([]byte(""))
|
||||
data["sign"] = base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
return n.postJSON(webhook, data)
|
||||
}
|
||||
|
||||
// ---- Bark ----
|
||||
// sendBark 封装sendBark业务协调。
|
||||
func (n *Notifier) sendBark(cfg map[string]any, message string) error {
|
||||
// server 用于本次流程后续判断的server
|
||||
server := strings.TrimRight(strOr(cfg, "server_url", "https://api.day.app"), "/")
|
||||
// deviceKey 用于本次流程后续判断的deviceKey
|
||||
deviceKey := strOr(cfg, "device_key", "")
|
||||
if deviceKey == "" {
|
||||
return fmt.Errorf("bark device_key 为空")
|
||||
}
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"device_key": deviceKey,
|
||||
"title": strOr(cfg, "title", "闲鱼自动回复通知"),
|
||||
"body": message,
|
||||
"sound": strOr(cfg, "sound", "default"),
|
||||
"group": strOr(cfg, "group", "xianyu"),
|
||||
}
|
||||
if // icon 用于本次流程后续判断的icon
|
||||
icon := strOr(cfg, "icon", ""); icon != "" {
|
||||
data["icon"] = icon
|
||||
}
|
||||
if // u 用于本次流程后续判断的u
|
||||
u := strOr(cfg, "url", ""); u != "" {
|
||||
data["url"] = u
|
||||
}
|
||||
return n.postJSON(server+"/push", data)
|
||||
}
|
||||
|
||||
// ---- Webhook ----
|
||||
// sendWebhook 封装sendWebhook业务协调。
|
||||
func (n *Notifier) sendWebhook(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("webhook_url 为空")
|
||||
}
|
||||
// method 用于本次流程后续判断的方法
|
||||
method := strings.ToUpper(strOr(cfg, "http_method", "POST"))
|
||||
// headers 用于本次流程后续判断的headers
|
||||
headers := map[string]any{}
|
||||
if // h 用于本次流程后续判断的h
|
||||
h := strOr(cfg, "headers", ""); h != "" {
|
||||
_ = json.Unmarshal([]byte(h), &headers)
|
||||
}
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"message": message,
|
||||
"timestamp": time.Now().Format("2006-01-02 15:04:05"),
|
||||
"source": "xianyu-auto-reply",
|
||||
}
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := json.Marshal(data)
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequest(method, webhook, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("webhook 状态码 %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- 企业微信 ----
|
||||
func (n *Notifier) sendWeChat(cfg map[string]any, message string) error {
|
||||
// webhook 用于本次流程后续判断的webhook
|
||||
webhook := strOr(cfg, "webhook_url", "")
|
||||
if webhook == "" {
|
||||
return fmt.Errorf("微信 webhook_url 为空")
|
||||
}
|
||||
return n.postJSON(webhook, map[string]any{
|
||||
"msgtype": "text",
|
||||
"text": map[string]any{"content": message},
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Telegram ----
|
||||
// sendTelegram 封装sendTelegram业务协调。
|
||||
func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
|
||||
// botToken 用于本次流程后续判断的bot令牌
|
||||
botToken := strOr(cfg, "bot_token", "")
|
||||
// chatID 用于本次流程后续判断的聊天ID
|
||||
chatID := strOr(cfg, "chat_id", "")
|
||||
if botToken == "" || chatID == "" {
|
||||
return fmt.Errorf("telegram bot_token/chat_id 不完整")
|
||||
}
|
||||
// endpoint 用于本次流程后续判断的endpoint
|
||||
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
|
||||
return n.postJSON(endpoint, map[string]any{
|
||||
"chat_id": chatID,
|
||||
"text": message,
|
||||
})
|
||||
}
|
||||
|
||||
// ---- 邮件 ----
|
||||
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
|
||||
// ctx、cancel 用于本次流程后续判断的ctx、cancel
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
// server 用于本次流程后续判断的server
|
||||
server := n.smtpConfigValue(ctx, cfg, "smtp_server", "")
|
||||
// port 用于本次流程后续判断的port
|
||||
port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587")
|
||||
// user 用于本次流程后续判断的用户
|
||||
user := n.smtpConfigValue(ctx, cfg, "smtp_user", "")
|
||||
// pass 用于本次流程后续判断的pass
|
||||
pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "")
|
||||
// useTLS 用于本次流程后续判断的useTLS
|
||||
useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true)
|
||||
// useSSL 用于本次流程后续判断的useSSL
|
||||
useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false)
|
||||
// fromAddress 用于本次流程后续判断的fromAddress
|
||||
fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "")
|
||||
// fromName 用于本次流程后续判断的from名称
|
||||
fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "")
|
||||
// legacyFrom 用于本次流程后续判断的legacyFrom
|
||||
legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "")
|
||||
// to 用于本次流程后续判断的to
|
||||
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
|
||||
if server == "" || user == "" || to == "" {
|
||||
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
|
||||
}
|
||||
if legacyFrom != "" {
|
||||
if // parsed、err 用于本次流程后续判断的parsed、err
|
||||
parsed, err := mail.ParseAddress(legacyFrom); err == nil && strings.Contains(parsed.Address, "@") {
|
||||
if fromAddress == "" {
|
||||
fromAddress = parsed.Address
|
||||
}
|
||||
if fromName == "" {
|
||||
fromName = parsed.Name
|
||||
}
|
||||
} else if fromName == "" {
|
||||
fromName = legacyFrom
|
||||
}
|
||||
}
|
||||
if fromAddress == "" {
|
||||
fromAddress = user
|
||||
}
|
||||
// from、err 用于本次流程后续判断的from、err
|
||||
from, err := mail.ParseAddress(fromAddress)
|
||||
if err != nil || !strings.Contains(from.Address, "@") {
|
||||
return fmt.Errorf("发件邮箱地址无效")
|
||||
}
|
||||
// recipient、err 用于本次流程后续判断的recipient、err
|
||||
recipient, err := mail.ParseAddress(to)
|
||||
if err != nil || !strings.Contains(recipient.Address, "@") {
|
||||
return fmt.Errorf("收件邮箱地址无效")
|
||||
}
|
||||
from.Name = fromName
|
||||
// fromHeader 用于本次流程后续判断的fromHeader
|
||||
fromHeader := from.Address
|
||||
if from.Name != "" {
|
||||
fromHeader = from.String()
|
||||
}
|
||||
// toHeader 用于本次流程后续判断的toHeader
|
||||
toHeader := recipient.Address
|
||||
if recipient.Name != "" {
|
||||
toHeader = recipient.String()
|
||||
}
|
||||
// addr 用于本次流程后续判断的addr
|
||||
addr := server + ":" + port
|
||||
// auth 用于本次流程后续判断的auth
|
||||
auth := smtp.PlainAuth("", user, pass, server)
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := strings.Join([]string{
|
||||
"From: " + fromHeader,
|
||||
"To: " + toHeader,
|
||||
"Subject: =?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte("闲鱼自动发货通知")) + "?=",
|
||||
"MIME-Version: 1.0",
|
||||
"Content-Type: text/plain; charset=UTF-8",
|
||||
"",
|
||||
message,
|
||||
}, "\r\n")
|
||||
return sendPublicSMTP(ctx, addr, server, auth, from.Address, recipient.Address, []byte(msg), smtpTransportOptions{
|
||||
UseSTARTTLS: useTLS && !useSSL,
|
||||
UseImplicitTLS: useSSL,
|
||||
})
|
||||
}
|
||||
|
||||
// smtpTransportOptions 用于本次流程后续判断的smtpTransportOptions
|
||||
type smtpTransportOptions struct {
|
||||
UseSTARTTLS bool
|
||||
UseImplicitTLS bool
|
||||
}
|
||||
|
||||
// sendPublicSMTP 封装sendPublicSMTP业务协调。
|
||||
func sendPublicSMTP(ctx context.Context, addr, server string, auth smtp.Auth, from, to string, message []byte, options ...smtpTransportOptions) error {
|
||||
// rawPort、err 用于本次流程后续判断的原始Port、err
|
||||
_, rawPort, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 地址无效")
|
||||
}
|
||||
// port、err 用于本次流程后续判断的port、err
|
||||
port, err := strconv.Atoi(strings.TrimSpace(rawPort))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return fmt.Errorf("SMTP 端口无效")
|
||||
}
|
||||
// conn、err 用于本次流程后续判断的conn、err
|
||||
conn, err := dialPublicSMTP(ctx, "tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接 SMTP 服务器失败: %w", err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
_ = conn.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
// transport 用于本次流程后续判断的transport
|
||||
transport := smtpTransportOptions{UseSTARTTLS: true}
|
||||
if len(options) > 0 {
|
||||
transport = options[0]
|
||||
}
|
||||
if transport.UseImplicitTLS {
|
||||
// tlsConn 用于本次流程后续判断的tlsConn
|
||||
tlsConn := tls.Client(conn, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: server})
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return fmt.Errorf("SMTP SSL 握手失败: %w", err)
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
// client、err 用于本次流程后续判断的client、err
|
||||
client, err := smtp.NewClient(conn, server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
if transport.UseSTARTTLS {
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
ok, _ := client.Extension("STARTTLS"); !ok {
|
||||
return fmt.Errorf("SMTP 服务器不支持要求的 STARTTLS")
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: server}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if auth != nil {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Auth(auth); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Mail(from); err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := client.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
// w、err 用于本次流程后续判断的w、err
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := w.Write(message); err != nil {
|
||||
_ = w.Close()
|
||||
return err
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Quit()
|
||||
}
|
||||
|
||||
// parseConfigBool 封装parse配置Bool业务协调。
|
||||
func parseConfigBool(raw string, fallback bool) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
case "0", "false", "no", "off":
|
||||
return false
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
// configOrSetting 封装配置Or设置业务协调。
|
||||
func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
if // v 用于本次流程后续判断的v
|
||||
v := strings.TrimSpace(strOr(cfg, key, "")); v != "" {
|
||||
return v
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // v、err 用于本次流程后续判断的v、err
|
||||
v, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// smtpConfigValue keeps legacy per-field fallback behavior for existing rows,
|
||||
// while new rows use an explicit all-system or all-channel SMTP mode.
|
||||
// smtpConfigValue 封装smtp配置值业务协调。
|
||||
func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
|
||||
// modeValue、hasExplicitMode 用于本次流程后续判断的模式Value、hasExplicit模式
|
||||
modeValue, hasExplicitMode := cfg["use_custom_smtp"]
|
||||
if !hasExplicitMode {
|
||||
return n.configOrSetting(ctx, cfg, key, fallbackValue)
|
||||
}
|
||||
if parseConfigBool(fmt.Sprintf("%v", modeValue), false) {
|
||||
if // value 用于本次流程后续判断的值
|
||||
value := strings.TrimSpace(strOr(cfg, key, "")); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
if n.repository != nil {
|
||||
if // value、err 用于本次流程后续判断的value、err
|
||||
value, err := n.repository.GetSetting(ctx, key); err == nil && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return fallbackValue
|
||||
}
|
||||
|
||||
// postJSON 通用 JSON POST。
|
||||
func (n *Notifier) postJSON(url string, payload any) error {
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// requestCtx、requestCancel 为单次渠道 HTTP 请求创建有界取消路径。
|
||||
requestCtx, requestCancel := context.WithTimeout(context.Background(), legacyNotifierOperationTimeout)
|
||||
defer requestCancel()
|
||||
// req、err 分别是携带取消语义的渠道 HTTP 请求及其构造错误。
|
||||
req, err := http.NewRequestWithContext(requestCtx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := n.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// responseBody、err 用于本次流程后续判断的响应Body、err
|
||||
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("状态码 %d", resp.StatusCode)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := notificationBusinessError(responseBody); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notificationBusinessError 封装通知Business错误业务协调。
|
||||
func notificationBusinessError(body []byte) error {
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return nil
|
||||
}
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) != nil {
|
||||
return nil
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := strings.TrimSpace(firstMapString(payload, "errmsg", "msg", "message", "description"))
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "errcode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "StatusCode"); ok && code != 0 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := mapNumber(payload, "code"); ok && code != 0 && code != 200 {
|
||||
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
|
||||
}
|
||||
if // okValue、exists 用于本次流程后续判断的okValue、exists
|
||||
okValue, exists := payload["ok"].(bool); exists && !okValue {
|
||||
return fmt.Errorf("通知渠道返回失败: %s", message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapNumber 封装mapNumber业务协调。
|
||||
func mapNumber(payload map[string]any, key string) (float64, bool) {
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
switch // typed 用于本次流程后续判断的typed
|
||||
typed := value.(type) {
|
||||
case float64:
|
||||
return typed, true
|
||||
case string:
|
||||
// number、err 用于本次流程后续判断的number、err
|
||||
number, err := strconv.ParseFloat(typed, 64)
|
||||
return number, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// firstMapString 封装firstMapString业务协调。
|
||||
func firstMapString(payload map[string]any, keys ...string) string {
|
||||
// key 表示当前遍历过程中的key
|
||||
for _, key := range keys {
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := payload[key].(string); ok && value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return "未知错误"
|
||||
}
|
||||
|
||||
// strOr 从 map 取字符串,缺失返回 fallback。
|
||||
func strOr(m map[string]any, key, fallback string) string {
|
||||
if // v、ok 用于本次流程后续判断的v、ok
|
||||
v, ok := m[key]; ok {
|
||||
switch // x 用于本次流程后续判断的x
|
||||
x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
default:
|
||||
return fmt.Sprintf("%v", x)
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// fallback 封装fallback业务协调。
|
||||
func fallback(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -2,12 +2,9 @@ package renewal
|
||||
|
||||
import (
|
||||
"context"
|
||||
crand "crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -774,218 +771,3 @@ func (s *Scheduler) wakeCredentialBlockedAutomation(ctx context.Context, cookieI
|
||||
}
|
||||
|
||||
// apiRenewEnabled 封装apiRenew启用状态业务协调。
|
||||
func (s *Scheduler) apiRenewEnabled(ctx context.Context) bool {
|
||||
if s.settingConfigured(ctx, apiCookieRenewEnabledSetting) {
|
||||
return s.settingEnabled(ctx, apiCookieRenewEnabledSetting, true)
|
||||
}
|
||||
return s.settingEnabled(ctx, cookiesRefreshEnabledSetting, true)
|
||||
}
|
||||
|
||||
// apiRenewInterval 封装apiRenewInterval业务协调。
|
||||
func (s *Scheduler) apiRenewInterval(ctx context.Context) time.Duration {
|
||||
if s.settingConfigured(ctx, apiCookieRenewIntervalSetting) {
|
||||
return s.settingInterval(ctx, apiCookieRenewIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
return s.settingInterval(ctx, cookiesRefreshIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
|
||||
// settingConfigured 封装设置Configured业务协调。
|
||||
func (s *Scheduler) settingConfigured(ctx context.Context, key string) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return false
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
return err == nil && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
// reloadRenewalAccount 封装reloadRenewal账号业务协调。
|
||||
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalRuntimeAccount) (db.RenewalRuntimeAccount, error) {
|
||||
// latest 是锁内重新读取的续期窄模型,用于避免批次列表中的旧 Cookie 覆盖新状态。
|
||||
latest, err := s.store.Cookies.GetRenewalRuntimeAccount(ctx, account.ID)
|
||||
if err != nil {
|
||||
return db.RenewalRuntimeAccount{}, err
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
/*
|
||||
reloadRenewalAccount 在每个账号续期前重新读取最新的 Cookie。
|
||||
重新读取同时复核账号启用状态,避免批次快照覆盖并发更新。
|
||||
repository 负责解密最小运行视图,不再展开登录用户名和密码。
|
||||
续期任务仍在账号凭证锁内调用此边界。
|
||||
Cookie 更新后的重启和自动化唤醒逻辑保持原有顺序。
|
||||
本次切片只收窄读取字段,不改变续期请求参数。
|
||||
禁用账号会由调用方根据 Enabled 字段跳过后续请求。
|
||||
查询失败仍由当前任务记录失败并结束该账号处理。
|
||||
后续的保存函数继续复用 UpdateRenewalCookie。
|
||||
它不代表新增的业务分支或兼容行为。
|
||||
窄模型中的 metadata 仍用于完整 Cookie Jar 恢复。
|
||||
Cookie 明文只在本次调用链中短暂存在。
|
||||
*/
|
||||
|
||||
// saveRenewedCookies 封装saveRenewedCookies业务协调。
|
||||
func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
s.logger.Warn("保存续期 Cookie 失败", "account", cookieID, "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// addLoginLog 封装add登录Log业务协调。
|
||||
func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status, message string, updated []string, duration time.Duration) {
|
||||
_ = s.store.Renewal.AddLoginRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: cookieID,
|
||||
Status: status,
|
||||
Message: message,
|
||||
UpdatedCookieNames: updated,
|
||||
RenewMethod: "loginuser.get",
|
||||
StepDetails: fmt.Sprintf("loginuser.get status=%s message=%s updated=%d", status, message, len(updated)),
|
||||
DurationMS: duration.Milliseconds(),
|
||||
RequestCount: 1,
|
||||
})
|
||||
}
|
||||
|
||||
// addAPILog 封装addAPILog业务协调。
|
||||
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Renewal.AddAPICookieRenewLog(ctx, log); err != nil {
|
||||
s.logger.Warn("记录 API Cookie 续期日志失败", "account", log.CookieID, "status", log.Status, "err", err)
|
||||
return
|
||||
}
|
||||
if s.notifier == nil || log.Status != "failed" || s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
// statuses、err 用于本次流程后续判断的statuses、err
|
||||
statuses, err := s.store.Renewal.RecentAPICookieRenewStatuses(ctx, log.CookieID, 4)
|
||||
if err != nil || len(statuses) < 3 || statuses[0] != "failed" || statuses[1] != "failed" || statuses[2] != "failed" {
|
||||
return
|
||||
}
|
||||
if len(statuses) >= 4 && statuses[3] == "failed" {
|
||||
return
|
||||
}
|
||||
// reason 用于本次流程后续判断的原因
|
||||
reason := strings.TrimSpace(log.ErrorMessage)
|
||||
if reason == "" {
|
||||
reason = strings.TrimSpace(log.Message)
|
||||
}
|
||||
if reason == "" {
|
||||
reason = "未知错误"
|
||||
}
|
||||
s.notifier.NotifyAccountEvent(log.CookieID, "token_renewal", "warn", "闲鱼 Cookie 自动续期连续失败", fmt.Sprintf("账号 %s 的 API 自动续期已连续失败 3 次,最近错误:%s", log.CookieID, reason))
|
||||
}
|
||||
|
||||
// cleanupExpiredLogs 封装cleanupExpiredLogs业务协调。
|
||||
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
||||
if s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
// days 用于本次流程后续判断的days
|
||||
days := s.settingInt(ctx, "renewal_log_retention_days", 10)
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Renewal.CleanupLogs(ctx, days); err != nil {
|
||||
s.logger.Warn("清理续期日志失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// markSessionExpired 封装mark会话Expired业务协调。
|
||||
func (s *Scheduler) markSessionExpired(cookieID string) {
|
||||
s.cooldown.MarkSessionExpired(cookieID)
|
||||
}
|
||||
|
||||
// isSessionCooled 封装is会话Cooled业务协调。
|
||||
func (s *Scheduler) isSessionCooled(cookieID string) bool {
|
||||
// ok 用于本次流程后续判断的ok
|
||||
ok, _ := s.cooldown.IsSessionCooled(cookieID)
|
||||
return ok
|
||||
}
|
||||
|
||||
// settingEnabled 封装设置启用状态业务协调。
|
||||
func (s *Scheduler) settingEnabled(ctx context.Context, key string, defaultEnabled bool) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultEnabled
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultEnabled
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes", "on", "enabled":
|
||||
return true
|
||||
case "0", "false", "no", "off", "disabled":
|
||||
return false
|
||||
default:
|
||||
return defaultEnabled
|
||||
}
|
||||
}
|
||||
|
||||
// settingInterval 封装设置Interval业务协调。
|
||||
func (s *Scheduler) settingInterval(ctx context.Context, key string, defaultInterval time.Duration) time.Duration {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultInterval
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultInterval
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if // seconds、err 用于本次流程后续判断的seconds、err
|
||||
seconds, err := strconv.ParseFloat(value, 64); err == nil && seconds > 0 {
|
||||
return time.Duration(seconds * float64(time.Second))
|
||||
}
|
||||
if // d、err 用于本次流程后续判断的d、err
|
||||
d, err := time.ParseDuration(value); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
return defaultInterval
|
||||
}
|
||||
|
||||
// settingInt 封装设置Int业务协调。
|
||||
func (s *Scheduler) settingInt(ctx context.Context, key string, defaultValue int) int {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultValue
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultValue
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil || n < 0 {
|
||||
return defaultValue
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// newBatchID 封装new批次ID业务协调。
|
||||
func newBatchID() string {
|
||||
// b 用于本次流程后续判断的b
|
||||
var b [16]byte
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := crand.Read(b[:]); err != nil {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// sleepCtx 封装sleepCtx业务协调。
|
||||
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||||
if d <= 0 {
|
||||
return nil
|
||||
}
|
||||
// timer 用于本次流程后续判断的定时器
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package renewal
|
||||
|
||||
import (
|
||||
"context"
|
||||
crand "crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// apiRenewEnabled 读取 API Cookie 续期开关,并在设置缺失时保留安全默认值。
|
||||
func (s *Scheduler) apiRenewEnabled(ctx context.Context) bool {
|
||||
if s.settingConfigured(ctx, apiCookieRenewEnabledSetting) {
|
||||
return s.settingEnabled(ctx, apiCookieRenewEnabledSetting, true)
|
||||
}
|
||||
return s.settingEnabled(ctx, cookiesRefreshEnabledSetting, true)
|
||||
}
|
||||
|
||||
// apiRenewInterval 封装apiRenewInterval业务协调。
|
||||
func (s *Scheduler) apiRenewInterval(ctx context.Context) time.Duration {
|
||||
if s.settingConfigured(ctx, apiCookieRenewIntervalSetting) {
|
||||
return s.settingInterval(ctx, apiCookieRenewIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
return s.settingInterval(ctx, cookiesRefreshIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
|
||||
// settingConfigured 封装设置Configured业务协调。
|
||||
func (s *Scheduler) settingConfigured(ctx context.Context, key string) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return false
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
return err == nil && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
// reloadRenewalAccount 封装reloadRenewal账号业务协调。
|
||||
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalRuntimeAccount) (db.RenewalRuntimeAccount, error) {
|
||||
// latest 是锁内重新读取的续期窄模型,用于避免批次列表中的旧 Cookie 覆盖新状态。
|
||||
latest, err := s.store.Cookies.GetRenewalRuntimeAccount(ctx, account.ID)
|
||||
if err != nil {
|
||||
return db.RenewalRuntimeAccount{}, err
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
/*
|
||||
reloadRenewalAccount 在每个账号续期前重新读取最新的 Cookie。
|
||||
重新读取同时复核账号启用状态,避免批次快照覆盖并发更新。
|
||||
repository 负责解密最小运行视图,不再展开登录用户名和密码。
|
||||
续期任务仍在账号凭证锁内调用此边界。
|
||||
Cookie 更新后的重启和自动化唤醒逻辑保持原有顺序。
|
||||
本次切片只收窄读取字段,不改变续期请求参数。
|
||||
禁用账号会由调用方根据 Enabled 字段跳过后续请求。
|
||||
查询失败仍由当前任务记录失败并结束该账号处理。
|
||||
后续的保存函数继续复用 UpdateRenewalCookie。
|
||||
它不代表新增的业务分支或兼容行为。
|
||||
窄模型中的 metadata 仍用于完整 Cookie Jar 恢复。
|
||||
Cookie 明文只在本次调用链中短暂存在。
|
||||
*/
|
||||
|
||||
// saveRenewedCookies 封装saveRenewedCookies业务协调。
|
||||
func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
s.logger.Warn("保存续期 Cookie 失败", "account", cookieID, "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// addLoginLog 封装add登录Log业务协调。
|
||||
func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status, message string, updated []string, duration time.Duration) {
|
||||
_ = s.store.Renewal.AddLoginRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: cookieID,
|
||||
Status: status,
|
||||
Message: message,
|
||||
UpdatedCookieNames: updated,
|
||||
RenewMethod: "loginuser.get",
|
||||
StepDetails: fmt.Sprintf("loginuser.get status=%s message=%s updated=%d", status, message, len(updated)),
|
||||
DurationMS: duration.Milliseconds(),
|
||||
RequestCount: 1,
|
||||
})
|
||||
}
|
||||
|
||||
// addAPILog 封装addAPILog业务协调。
|
||||
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Renewal.AddAPICookieRenewLog(ctx, log); err != nil {
|
||||
s.logger.Warn("记录 API Cookie 续期日志失败", "account", log.CookieID, "status", log.Status, "err", err)
|
||||
return
|
||||
}
|
||||
if s.notifier == nil || log.Status != "failed" || s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
// statuses、err 用于本次流程后续判断的statuses、err
|
||||
statuses, err := s.store.Renewal.RecentAPICookieRenewStatuses(ctx, log.CookieID, 4)
|
||||
if err != nil || len(statuses) < 3 || statuses[0] != "failed" || statuses[1] != "failed" || statuses[2] != "failed" {
|
||||
return
|
||||
}
|
||||
if len(statuses) >= 4 && statuses[3] == "failed" {
|
||||
return
|
||||
}
|
||||
// reason 用于本次流程后续判断的原因
|
||||
reason := strings.TrimSpace(log.ErrorMessage)
|
||||
if reason == "" {
|
||||
reason = strings.TrimSpace(log.Message)
|
||||
}
|
||||
if reason == "" {
|
||||
reason = "未知错误"
|
||||
}
|
||||
s.notifier.NotifyAccountEvent(log.CookieID, "token_renewal", "warn", "闲鱼 Cookie 自动续期连续失败", fmt.Sprintf("账号 %s 的 API 自动续期已连续失败 3 次,最近错误:%s", log.CookieID, reason))
|
||||
}
|
||||
|
||||
// cleanupExpiredLogs 封装cleanupExpiredLogs业务协调。
|
||||
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
||||
if s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
// days 用于本次流程后续判断的days
|
||||
days := s.settingInt(ctx, "renewal_log_retention_days", 10)
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := s.store.Renewal.CleanupLogs(ctx, days); err != nil {
|
||||
s.logger.Warn("清理续期日志失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// markSessionExpired 封装mark会话Expired业务协调。
|
||||
func (s *Scheduler) markSessionExpired(cookieID string) {
|
||||
s.cooldown.MarkSessionExpired(cookieID)
|
||||
}
|
||||
|
||||
// isSessionCooled 封装is会话Cooled业务协调。
|
||||
func (s *Scheduler) isSessionCooled(cookieID string) bool {
|
||||
// ok 用于本次流程后续判断的ok
|
||||
ok, _ := s.cooldown.IsSessionCooled(cookieID)
|
||||
return ok
|
||||
}
|
||||
|
||||
// settingEnabled 封装设置启用状态业务协调。
|
||||
func (s *Scheduler) settingEnabled(ctx context.Context, key string, defaultEnabled bool) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultEnabled
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultEnabled
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes", "on", "enabled":
|
||||
return true
|
||||
case "0", "false", "no", "off", "disabled":
|
||||
return false
|
||||
default:
|
||||
return defaultEnabled
|
||||
}
|
||||
}
|
||||
|
||||
// settingInterval 封装设置Interval业务协调。
|
||||
func (s *Scheduler) settingInterval(ctx context.Context, key string, defaultInterval time.Duration) time.Duration {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultInterval
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultInterval
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if // seconds、err 用于本次流程后续判断的seconds、err
|
||||
seconds, err := strconv.ParseFloat(value, 64); err == nil && seconds > 0 {
|
||||
return time.Duration(seconds * float64(time.Second))
|
||||
}
|
||||
if // d、err 用于本次流程后续判断的d、err
|
||||
d, err := time.ParseDuration(value); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
return defaultInterval
|
||||
}
|
||||
|
||||
// settingInt 封装设置Int业务协调。
|
||||
func (s *Scheduler) settingInt(ctx context.Context, key string, defaultValue int) int {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultValue
|
||||
}
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
if err != nil || strings.TrimSpace(value) == "" {
|
||||
return defaultValue
|
||||
}
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil || n < 0 {
|
||||
return defaultValue
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// newBatchID 封装new批次ID业务协调。
|
||||
func newBatchID() string {
|
||||
// b 用于本次流程后续判断的b
|
||||
var b [16]byte
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := crand.Read(b[:]); err != nil {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// sleepCtx 封装sleepCtx业务协调。
|
||||
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||||
if d <= 0 {
|
||||
return nil
|
||||
}
|
||||
// timer 用于本次流程后续判断的定时器
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
)
|
||||
|
||||
// operationResponse 是密码、会话和设置变更接口共用的操作结果 DTO。
|
||||
@@ -790,787 +785,3 @@ type orderImportResultDTO struct {
|
||||
// Message 是当前订单的处理说明。
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// aiReplySettingsResponse 是账号 AI 回复设置接口的具名响应 DTO。
|
||||
type aiReplySettingsResponse struct {
|
||||
// CookieID 是账号稳定标识;默认配置响应省略该字段。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// AIEnabled 表示账号 AI 回复是否启用。
|
||||
AIEnabled bool `json:"ai_enabled"`
|
||||
// MaxDiscountPercent 是允许的最大折扣比例。
|
||||
MaxDiscountPercent int `json:"max_discount_percent"`
|
||||
// MaxDiscountAmount 是允许的最大折扣金额。
|
||||
MaxDiscountAmount int `json:"max_discount_amount"`
|
||||
// MaxBargainRounds 是允许的最大砍价轮次。
|
||||
MaxBargainRounds int `json:"max_bargain_rounds"`
|
||||
// CustomPrompts 是账号自定义提示词。
|
||||
CustomPrompts string `json:"custom_prompts"`
|
||||
}
|
||||
|
||||
// aiModelsResponse 是 AI 模型发现接口的具名响应 DTO。
|
||||
type aiModelsResponse struct {
|
||||
// Models 是远端可用模型名称列表。
|
||||
Models []string `json:"models"`
|
||||
}
|
||||
|
||||
// userSettingResponse 是单个用户设置查询接口的具名响应 DTO。
|
||||
type userSettingResponse struct {
|
||||
// Value 是设置值文本。
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// cardResponse 是卡券详情和列表接口的具名响应 DTO。
|
||||
type cardResponse struct {
|
||||
// ID 是卡券组稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// Name 是卡券组名称。
|
||||
Name string `json:"name"`
|
||||
// Type 是卡券类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是 API 卡券配置 JSON。
|
||||
APIConfig string `json:"api_config"`
|
||||
// TextContent 是文本卡券内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是批量数据卡券内容。
|
||||
DataContent string `json:"data_content"`
|
||||
// ImageURL 是图片卡券地址。
|
||||
ImageURL string `json:"image_url"`
|
||||
// Description 是卡券组描述。
|
||||
Description string `json:"description"`
|
||||
// Enabled 表示卡券组是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// DelaySeconds 是自动发货延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
// IsMultiSpec 表示卡券组是否按规格区分。
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
// SpecName 是卡券规格名称。
|
||||
SpecName string `json:"spec_name"`
|
||||
// SpecValue 是卡券规格值。
|
||||
SpecValue string `json:"spec_value"`
|
||||
// UserID 是卡券所属用户标识,保留旧接口字段。
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// cardBatchResponse 是卡券批量创建接口的具名响应 DTO。
|
||||
type cardBatchResponse struct {
|
||||
// Success 表示批量解析和处理流程已完成。
|
||||
Success bool `json:"success"`
|
||||
// Total 是表格中解析出的数据行数量。
|
||||
Total int `json:"total"`
|
||||
// Created 是成功创建的卡券组数量。
|
||||
Created int `json:"created"`
|
||||
// Failed 是创建失败的数据行数量。
|
||||
Failed int `json:"failed"`
|
||||
// Rows 是逐行处理结果。
|
||||
Rows []cardBatchResultRow `json:"rows"`
|
||||
}
|
||||
|
||||
// cardAppendResponse 是追加卡密接口的具名响应 DTO。
|
||||
type cardAppendResponse struct {
|
||||
// Success 表示追加操作是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Added 是实际追加的卡密数量。
|
||||
Added int `json:"added"`
|
||||
}
|
||||
|
||||
// notificationChannelResponse 是通知渠道接口的具名响应 DTO。
|
||||
type notificationChannelResponse struct {
|
||||
// ID 是通知渠道稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// Name 是通知渠道名称。
|
||||
Name string `json:"name"`
|
||||
// Type 是通知渠道类型。
|
||||
Type string `json:"type"`
|
||||
// EventTypes 是订阅事件类型 JSON 或兼容分隔文本。
|
||||
EventTypes string `json:"event_types,omitempty"`
|
||||
// Enabled 表示通知渠道是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// UserID 是渠道所属用户标识,保留旧接口字段。
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newNotificationChannelResponse 将数据库通知渠道转换为 HTTP DTO。
|
||||
func newNotificationChannelResponse(channel notificationsapp.ChannelSummary) notificationChannelResponse {
|
||||
return notificationChannelResponse{
|
||||
ID: channel.ID, Name: channel.Name, Type: channel.Type,
|
||||
EventTypes: channel.EventTypes, Enabled: channel.Enabled, UserID: channel.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newNotificationChannelResponses 批量转换通知渠道,保持数据库模型不穿透 HTTP 层。
|
||||
func newNotificationChannelResponses(channels []notificationsapp.ChannelSummary) []notificationChannelResponse {
|
||||
// result 是转换后的通知渠道 DTO 列表。
|
||||
result := make([]notificationChannelResponse, 0, len(channels))
|
||||
// channel 是当前待转换的通知渠道数据库模型。
|
||||
for _, channel := range channels {
|
||||
result = append(result, newNotificationChannelResponse(channel))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// notificationBindingResponse 是单条账号通知绑定的具名 DTO。
|
||||
type notificationBindingResponse struct {
|
||||
// ID 是绑定记录稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ChannelID 是通知渠道标识。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// ChannelName 是通知渠道名称。
|
||||
ChannelName string `json:"channel_name"`
|
||||
// Enabled 表示该账号绑定是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// notificationBindingListResponse 是按账号分组的通知绑定响应 DTO。
|
||||
type notificationBindingListResponse map[string][]notificationBindingResponse
|
||||
|
||||
// accountBindingsResponse 是账号与通知渠道绑定查询接口的具名响应 DTO。
|
||||
type accountBindingsResponse struct {
|
||||
// CookieID 是账号稳定标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// ChannelIDs 是当前账号绑定的通知渠道标识列表。
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxItem 是不确定通知的非敏感运维摘要。
|
||||
// 该 DTO 不包含通知正文、渠道配置、凭证或最后错误原文。
|
||||
type notificationUncertainOutboxItem struct {
|
||||
// ID 是通知 outbox 记录的稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ChannelID 是关联通知渠道标识。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// OwnerUserID 是渠道所属用户标识,仅管理员查询时返回。
|
||||
OwnerUserID int64 `json:"owner_user_id,omitempty"`
|
||||
// EventType 是通知事件分类。
|
||||
EventType string `json:"event_type"`
|
||||
// AttemptCount 是进入不确定状态前的发送尝试次数。
|
||||
AttemptCount int `json:"attempt_count"`
|
||||
// UncertainAt 是进入不确定状态的 Unix 秒时间戳。
|
||||
UncertainAt int64 `json:"uncertain_at"`
|
||||
// HasError 表示是否存在本地确认错误,但不暴露错误原文。
|
||||
HasError bool `json:"has_error"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxResponse 是用户或管理员查询不确定通知的具名响应。
|
||||
type notificationUncertainOutboxResponse struct {
|
||||
// Total 是当前权限范围内的不确定通知总数。
|
||||
Total int `json:"total"`
|
||||
// Items 是按最近进入不确定状态排序的非敏感摘要列表。
|
||||
Items []notificationUncertainOutboxItem `json:"items"`
|
||||
}
|
||||
|
||||
// newNotificationUncertainOutboxResponse 将应用层不确定状态摘要转换为非敏感 HTTP DTO。
|
||||
// includeOwner 仅管理员列表使用,用于展示渠道所属用户但不改变正文脱敏边界。
|
||||
func newNotificationUncertainOutboxResponse(items []notificationsapp.UncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse {
|
||||
// result 保存不确定通知查询的具名响应。
|
||||
result := notificationUncertainOutboxResponse{Total: total, Items: make([]notificationUncertainOutboxItem, 0, len(items))}
|
||||
// item 保存当前待转换的应用层摘要。
|
||||
for _, item := range items {
|
||||
// responseItem 保存当前摘要对应的非敏感 API 行。
|
||||
responseItem := notificationUncertainOutboxItem{
|
||||
ID: item.ID, ChannelID: item.ChannelID, EventType: item.EventType,
|
||||
AttemptCount: item.AttemptCount, UncertainAt: item.UncertainAt, HasError: item.HasError,
|
||||
}
|
||||
if includeOwner {
|
||||
responseItem.OwnerUserID = item.OwnerUserID
|
||||
}
|
||||
result.Items = append(result.Items, responseItem)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// categoryRecommendationResponse 是商品类目推荐接口的具名响应 DTO。
|
||||
type categoryRecommendationResponse struct {
|
||||
// Success 表示类目推荐是否成功。
|
||||
Success bool `json:"success"`
|
||||
// Category 是推荐的商品类目。
|
||||
Category publishCategoryResponse `json:"category"`
|
||||
}
|
||||
|
||||
// publishCategoryResponse 是商品类目 HTTP 响应的稳定 DTO,不泄露平台包类型。
|
||||
type publishCategoryResponse struct {
|
||||
// CatID 是平台类目标识。
|
||||
CatID string `json:"cat_id"`
|
||||
// CatName 是平台类目名称。
|
||||
CatName string `json:"cat_name"`
|
||||
// ChannelCatID 是闲鱼频道类目标识。
|
||||
ChannelCatID string `json:"channel_cat_id,omitempty"`
|
||||
// TBCatID 是淘宝类目标识。
|
||||
TBCatID string `json:"tb_cat_id,omitempty"`
|
||||
}
|
||||
|
||||
// publishAutomationConfig 是批量发布预检与详情响应中的自动化配置 DTO。
|
||||
type publishAutomationConfig struct {
|
||||
// PaidDelivery 保存付款后自动发货配置。
|
||||
PaidDelivery publishCardAutomation `json:"paid_delivery"`
|
||||
// ReviewGift 保存评价后赠品配置。
|
||||
ReviewGift publishCardAutomation `json:"review_gift"`
|
||||
// ReviewRequest 保存超时求评价配置。
|
||||
ReviewRequest publishReviewRequestCfg `json:"review_request"`
|
||||
}
|
||||
|
||||
// publishCardAutomation 是批量发布中的卡密自动化 DTO。
|
||||
type publishCardAutomation struct {
|
||||
// Enabled 表示该自动化规则是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// Actions 保存按顺序执行的卡密动作。
|
||||
Actions []publishCardAction `json:"actions"`
|
||||
// ParseError 保存导入动作文本的解析错误。
|
||||
ParseError string `json:"-"`
|
||||
}
|
||||
|
||||
// publishCardAction 是单条批量卡密动作 DTO。
|
||||
type publishCardAction struct {
|
||||
// CardID 是卡密组标识。
|
||||
CardID int64 `json:"card_id"`
|
||||
// DeliveryCount 是每件商品发送的卡密数量。
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
// DelaySeconds 是发送动作的延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
// publishReviewRequestCfg 是批量发布求评价配置 DTO。
|
||||
type publishReviewRequestCfg struct {
|
||||
// Enabled 表示是否启用求评价。
|
||||
Enabled bool `json:"enabled"`
|
||||
// AfterShippedHours 是发货后的等待小时数。
|
||||
AfterShippedHours int `json:"after_shipped_hours"`
|
||||
// Message 是发送给买家的求评价文案。
|
||||
Message string `json:"message"`
|
||||
// MaxAttempts 是最多提醒次数。
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
// DelaySeconds 是提醒动作的延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
// itemPublishBatchPreviewResponse 是商品批量发布预检接口的具名响应 DTO。
|
||||
type itemPublishBatchPreviewResponse struct {
|
||||
// Success 表示预检是否完成。
|
||||
Success bool `json:"success"`
|
||||
// PreviewID 是后续启动批量发布使用的预检批次标识。
|
||||
PreviewID string `json:"preview_id"`
|
||||
// Total 是预检数据行总数。
|
||||
Total int `json:"total"`
|
||||
// Valid 是通过预检的数据行数量。
|
||||
Valid int `json:"valid"`
|
||||
// Invalid 是未通过预检的数据行数量。
|
||||
Invalid int `json:"invalid"`
|
||||
// Rows 是逐行预检结果。
|
||||
Rows []publishBatchPreviewRow `json:"rows"`
|
||||
}
|
||||
|
||||
// batchIDResponse 是商品批量任务启动或重试接口的具名响应 DTO。
|
||||
type batchIDResponse struct {
|
||||
// Success 表示任务操作是否完成。
|
||||
Success bool `json:"success"`
|
||||
// BatchID 是商品批量任务标识。
|
||||
BatchID string `json:"batch_id"`
|
||||
}
|
||||
|
||||
// batchCancelResponse 是商品批量任务取消接口的具名响应 DTO。
|
||||
type batchCancelResponse struct {
|
||||
// Success 表示取消请求是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Status 是任务取消后的状态。
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// itemPublishBatchRowResponse 是商品批量任务逐行详情 DTO。
|
||||
type itemPublishBatchRowResponse struct {
|
||||
// ID 是批量任务明细行主键。
|
||||
ID int64 `json:"id"`
|
||||
// RowNo 是导入表格中的行号。
|
||||
RowNo int `json:"row_no"`
|
||||
// CookieID 是商品发布目标账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// Title 是商品标题。
|
||||
Title string `json:"title"`
|
||||
// Price 是商品价格文本。
|
||||
Price string `json:"price"`
|
||||
// Quantity 是商品库存数量。
|
||||
Quantity int `json:"quantity"`
|
||||
// Images 是商品图片引用列表。
|
||||
Images []string `json:"images"`
|
||||
// Category 是商品发布类目。
|
||||
Category publishCategoryResponse `json:"category"`
|
||||
// Automation 是发布后自动化配置。
|
||||
Automation publishAutomationConfig `json:"automation"`
|
||||
// Status 是当前明细行状态。
|
||||
Status string `json:"status"`
|
||||
// ItemID 是发布成功后的平台商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemURL 是发布成功后的商品地址。
|
||||
ItemURL string `json:"item_url"`
|
||||
// ErrorMessage 是明细行失败原因。
|
||||
ErrorMessage string `json:"error_message"`
|
||||
// FailureKind 是失败类型。
|
||||
FailureKind string `json:"failure_kind"`
|
||||
}
|
||||
|
||||
// itemPublishBatchResponse 是商品批量任务详情接口的具名响应 DTO。
|
||||
type itemPublishBatchResponse struct {
|
||||
// ID 是商品批量任务标识。
|
||||
ID string `json:"id"`
|
||||
// Status 是批量任务状态。
|
||||
Status string `json:"status"`
|
||||
// Filename 是原始上传文件名。
|
||||
Filename string `json:"filename"`
|
||||
// Total 是明细行总数。
|
||||
Total int `json:"total"`
|
||||
// Success 是成功发布的明细行数量,保留旧字段名称。
|
||||
Success int `json:"success"`
|
||||
// Failed 是失败明细行数量。
|
||||
Failed int `json:"failed"`
|
||||
// Pending 是待处理明细行数量。
|
||||
Pending int `json:"pending"`
|
||||
// Running 是正在处理明细行数量。
|
||||
Running int `json:"running"`
|
||||
// Retryable 是可重试明细行数量。
|
||||
Retryable int `json:"retryable"`
|
||||
// Rows 是批量任务逐行结果。
|
||||
Rows []itemPublishBatchRowResponse `json:"rows"`
|
||||
// Location 是批次统一发货地对象。
|
||||
Location any `json:"location"`
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int `json:"publish_interval_seconds"`
|
||||
// CreatedAt 是任务创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// UpdatedAt 是任务更新时间。
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// itemPublishBatchListResponse 是商品批量任务列表接口的具名响应 DTO。
|
||||
type itemPublishBatchListResponse struct {
|
||||
// Batches 是当前用户的商品批量任务列表。
|
||||
Batches []itemPublishBatchResponse `json:"batches"`
|
||||
}
|
||||
|
||||
// keywordBasicResponse 是传统关键词接口的基础响应 DTO。
|
||||
type keywordBasicResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
}
|
||||
|
||||
// keywordItemResponse 是带商品范围的关键词响应 DTO。
|
||||
type keywordItemResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
}
|
||||
|
||||
// keywordTypedResponse 是支持文本/图片类型的关键词响应 DTO。
|
||||
type keywordTypedResponse struct {
|
||||
// ID 是关键词规则主键。
|
||||
ID int64 `json:"id"`
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// Type 是回复类型。
|
||||
Type string `json:"type"`
|
||||
// ImageURL 是图片回复地址。
|
||||
ImageURL string `json:"image_url"`
|
||||
}
|
||||
|
||||
// itemReplyResponse 是指定商品回复接口的具名 DTO。
|
||||
type itemReplyResponse struct {
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
// CookieID 是账号稳定标识。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// ReplyContent 是指定商品的回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
}
|
||||
|
||||
// defaultReplyResponse 是默认回复接口的具名 DTO。
|
||||
type defaultReplyResponse struct {
|
||||
// CookieID 是账号稳定标识;单账号查询响应可以省略。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// Enabled 表示默认回复是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// ReplyContent 是默认文字回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
// ReplyImageURL 是默认图片回复地址。
|
||||
ReplyImageURL string `json:"reply_image_url,omitempty"`
|
||||
// ReplyOnce 表示是否只回复一次。
|
||||
ReplyOnce bool `json:"reply_once"`
|
||||
}
|
||||
|
||||
// newDefaultReplyResponse 将默认回复应用模型转换为 HTTP DTO。
|
||||
func newDefaultReplyResponse(cookieID string, reply defaultreplyapp.Reply) defaultReplyResponse {
|
||||
return defaultReplyResponse{
|
||||
CookieID: cookieID, Enabled: reply.Enabled, ReplyContent: reply.ReplyContent,
|
||||
ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce,
|
||||
}
|
||||
}
|
||||
|
||||
// accountTaskSettingsResponse 是账号任务设置接口的具名 DTO。
|
||||
type accountTaskSettingsResponse struct {
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// AutoRateEnabled 表示自动评价是否启用。
|
||||
AutoRateEnabled bool `json:"auto_rate_enabled"`
|
||||
// RateContent 是自动评价文案。
|
||||
RateContent string `json:"rate_content"`
|
||||
// AutoPolishEnabled 表示自动擦亮是否启用。
|
||||
AutoPolishEnabled bool `json:"auto_polish_enabled"`
|
||||
// PolishTime 是自动擦亮本地时间。
|
||||
PolishTime string `json:"polish_time"`
|
||||
// LastRateScanAt 是最近一次评价扫描时间。
|
||||
LastRateScanAt int64 `json:"last_rate_scan_at"`
|
||||
// LastPolishDate 是最近一次擦亮日期。
|
||||
LastPolishDate string `json:"last_polish_date"`
|
||||
// LastPolishAt 是最近一次擦亮时间。
|
||||
LastPolishAt int64 `json:"last_polish_at"`
|
||||
}
|
||||
|
||||
// accountTaskRunResponse 是账号任务执行记录的具名 DTO。
|
||||
type accountTaskRunResponse struct {
|
||||
// ID 是任务执行记录主键。
|
||||
ID int64 `json:"id"`
|
||||
// RunKey 是任务幂等键。
|
||||
RunKey string `json:"run_key"`
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// TargetID 是任务目标标识。
|
||||
TargetID string `json:"target_id"`
|
||||
// RunDate 是任务业务日期。
|
||||
RunDate string `json:"run_date"`
|
||||
// Status 是任务执行状态。
|
||||
Status string `json:"status"`
|
||||
// SuccessCount 是任务成功数量。
|
||||
SuccessCount int `json:"success_count"`
|
||||
// FailedCount 是任务失败数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// ErrorMessage 是任务失败说明。
|
||||
ErrorMessage string `json:"error_message"`
|
||||
// NextRetryAt 是下一次重试时间。
|
||||
NextRetryAt int64 `json:"next_retry_at"`
|
||||
// StartedAt 是任务开始时间。
|
||||
StartedAt int64 `json:"started_at"`
|
||||
// FinishedAt 是任务完成时间。
|
||||
FinishedAt int64 `json:"finished_at"`
|
||||
}
|
||||
|
||||
// accountTaskSummaryResponse 是手动执行账号任务的统计 DTO。
|
||||
type accountTaskSummaryResponse struct {
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// Found 是发现的目标数量。
|
||||
Found int `json:"found"`
|
||||
// Success 是成功处理数量。
|
||||
Success int `json:"success"`
|
||||
// Failed 是失败处理数量。
|
||||
Failed int `json:"failed"`
|
||||
// Skipped 是跳过数量。
|
||||
Skipped int `json:"skipped"`
|
||||
// Message 是任务结果说明。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// accountTaskRunResponseEnvelope 是手动执行账号任务的具名响应 DTO。
|
||||
type accountTaskRunResponseEnvelope struct {
|
||||
// Success 表示任务请求是否成功完成。
|
||||
Success bool `json:"success"`
|
||||
// Summary 是账号任务执行统计。
|
||||
Summary accountTaskSummaryResponse `json:"summary"`
|
||||
}
|
||||
|
||||
// accountTaskRunsResponse 是账号任务执行记录列表的具名响应 DTO。
|
||||
type accountTaskRunsResponse struct {
|
||||
// Runs 是当前账号最近的任务执行记录。
|
||||
Runs []accountTaskRunResponse `json:"runs"`
|
||||
}
|
||||
|
||||
// adminUserResponse 是管理员用户列表项的具名响应 DTO。
|
||||
type adminUserResponse struct {
|
||||
// ID 是用户主键。
|
||||
ID int64 `json:"id"`
|
||||
// Username 是用户登录名。
|
||||
Username string `json:"username"`
|
||||
// Email 是用户邮箱。
|
||||
Email string `json:"email"`
|
||||
// IsActive 表示用户是否启用。
|
||||
IsActive bool `json:"is_active"`
|
||||
// IsAdmin 表示用户是否为管理员。
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
// CreatedAt 是用户创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// CookieCount 是用户拥有的账号数量。
|
||||
CookieCount int `json:"cookie_count"`
|
||||
}
|
||||
|
||||
// adminCookieResponse 是管理员账号列表项的具名响应 DTO。
|
||||
type adminCookieResponse struct {
|
||||
// ID 是账号稳定标识。
|
||||
ID string `json:"id"`
|
||||
// UserID 是账号所属用户主键。
|
||||
UserID int64 `json:"user_id"`
|
||||
// Remark 是账号备注。
|
||||
Remark string `json:"remark"`
|
||||
// CreatedAt 是账号创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// Owner 是账号所属用户名。
|
||||
Owner string `json:"owner"`
|
||||
// Enabled 表示账号是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// adminStatsResponse 是管理员全局统计的具名响应 DTO。
|
||||
type adminStatsResponse struct {
|
||||
// TotalUsers 是用户总数。
|
||||
TotalUsers int64 `json:"total_users"`
|
||||
// TotalCookies 是账号总数。
|
||||
TotalCookies int64 `json:"total_cookies"`
|
||||
// ActiveCookies 是活跃账号数。
|
||||
ActiveCookies int64 `json:"active_cookies"`
|
||||
// TotalCards 是卡券总数。
|
||||
TotalCards int64 `json:"total_cards"`
|
||||
// TotalKeywords 是关键词规则总数。
|
||||
TotalKeywords int64 `json:"total_keywords"`
|
||||
// TotalOrders 是有效订单总数。
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
}
|
||||
|
||||
// dashboardStatsResponse 是当前用户数据概览的具名响应 DTO。
|
||||
type dashboardStatsResponse struct {
|
||||
// TotalCookies 是账号总数。
|
||||
TotalCookies int64 `json:"total_cookies"`
|
||||
// ActiveCookies 是活跃账号数。
|
||||
ActiveCookies int64 `json:"active_cookies"`
|
||||
// TotalCards 是卡券总数。
|
||||
TotalCards int64 `json:"total_cards"`
|
||||
// AvailableCardStock 是可用卡券库存数量。
|
||||
AvailableCardStock int64 `json:"available_card_stock"`
|
||||
// TotalKeywords 是关键词规则总数。
|
||||
TotalKeywords int64 `json:"total_keywords"`
|
||||
// TotalOrders 是订单总数。
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
}
|
||||
|
||||
// analyticsRevenueStatsResponse 是订单收益统计的具名 DTO。
|
||||
type analyticsRevenueStatsResponse struct {
|
||||
// TotalOrders 是统计范围内的订单数。
|
||||
TotalOrders int `json:"total_orders"`
|
||||
// TotalAmount 是统计范围内的订单总金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
// AvgAmount 是订单平均金额。
|
||||
AvgAmount float64 `json:"avg_amount"`
|
||||
// UniqueBuyers 是买家数量。
|
||||
UniqueBuyers int `json:"unique_buyers"`
|
||||
// UniqueItems 是商品数量。
|
||||
UniqueItems int `json:"unique_items"`
|
||||
}
|
||||
|
||||
// analyticsDailyStatsResponse 是按日期聚合的订单统计 DTO。
|
||||
type analyticsDailyStatsResponse struct {
|
||||
// Date 是用户本地日期。
|
||||
Date string `json:"date"`
|
||||
// OrderCount 是当天订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// Amount 是当天订单金额。
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
// analyticsStatusStatsResponse 是按订单状态聚合的统计 DTO。
|
||||
type analyticsStatusStatsResponse struct {
|
||||
// Status 是归一化后的订单状态。
|
||||
Status string `json:"status"`
|
||||
// Count 是该状态订单数。
|
||||
Count int `json:"count"`
|
||||
// Amount 是该状态订单金额。
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
// analyticsCityStatsResponse 是按收货城市聚合的统计 DTO。
|
||||
type analyticsCityStatsResponse struct {
|
||||
// City 是收货城市。
|
||||
City string `json:"city"`
|
||||
// OrderCount 是该城市订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// TotalAmount 是该城市订单金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
}
|
||||
|
||||
// analyticsItemStatsResponse 是按商品聚合的统计 DTO。
|
||||
type analyticsItemStatsResponse struct {
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// OrderCount 是该商品订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// TotalAmount 是该商品订单金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
// AvgAmount 是该商品订单平均金额。
|
||||
AvgAmount float64 `json:"avg_amount"`
|
||||
}
|
||||
|
||||
// orderAnalyticsResponse 是订单分析接口的具名响应 DTO。
|
||||
type orderAnalyticsResponse struct {
|
||||
// RevenueStats 是收益统计。
|
||||
RevenueStats analyticsRevenueStatsResponse `json:"revenue_stats"`
|
||||
// DailyStats 是按日统计。
|
||||
DailyStats []analyticsDailyStatsResponse `json:"daily_stats"`
|
||||
// StatusStats 是按状态统计。
|
||||
StatusStats []analyticsStatusStatsResponse `json:"status_stats"`
|
||||
// CityStats 是按城市统计。
|
||||
CityStats []analyticsCityStatsResponse `json:"city_stats"`
|
||||
// ItemStats 是按商品统计。
|
||||
ItemStats []analyticsItemStatsResponse `json:"item_stats"`
|
||||
}
|
||||
|
||||
// validOrderResponse 是有效订单明细项的具名响应 DTO。
|
||||
type validOrderResponse struct {
|
||||
// OrderID 是平台订单标识。
|
||||
OrderID string `json:"order_id"`
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string `json:"buyer_id"`
|
||||
// ItemTitle 是商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemImage 是商品图片地址。
|
||||
ItemImage string `json:"item_image"`
|
||||
// Quantity 是订单数量文本。
|
||||
Quantity string `json:"quantity"`
|
||||
// Amount 是订单金额文本。
|
||||
Amount string `json:"amount"`
|
||||
// OrderStatus 是兼容保留的订单状态字段。
|
||||
OrderStatus string `json:"order_status"`
|
||||
// Status 是归一化后的订单状态。
|
||||
Status string `json:"status"`
|
||||
// CookieID 是订单所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// CreatedAt 是订单创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// validOrdersResponse 是有效订单分页查询的具名响应 DTO。
|
||||
type validOrdersResponse struct {
|
||||
// Orders 是当前页有效订单。
|
||||
Orders []validOrderResponse `json:"orders"`
|
||||
// Total 是符合条件的订单总数。
|
||||
Total int `json:"total"`
|
||||
// Page 是当前页码。
|
||||
Page int `json:"page"`
|
||||
// PageSize 是当前页大小。
|
||||
PageSize int `json:"page_size"`
|
||||
// Truncated 表示是否还有未返回的订单。
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
// qrLoginGenerateResponse 是扫码登录二维码生成的具名响应 DTO。
|
||||
type qrLoginGenerateResponse struct {
|
||||
// Success 表示二维码是否生成成功。
|
||||
Success bool `json:"success"`
|
||||
// SessionID 是扫码登录会话标识。
|
||||
SessionID string `json:"session_id"`
|
||||
// QRCodeURL 是二维码图片地址。
|
||||
QRCodeURL string `json:"qr_code_url"`
|
||||
// Message 是可选的提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// settingsEntryDTO 是单条设置键值的具名 DTO;仅在 HTTP 边界内部用于稳定排序和校验。
|
||||
type settingsEntryDTO struct {
|
||||
// Key 是设置项的稳定键名。
|
||||
Key string `json:"key"`
|
||||
// Value 是设置项的脱敏文本值。
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// settingsResponse 是设置查询的具名响应 DTO;序列化时保持旧客户端的顶层键值对象形状。
|
||||
type settingsResponse struct {
|
||||
// Entries 保存设置键值,避免 DTO 直接暴露动态 map 字段。
|
||||
Entries []settingsEntryDTO `json:"-"`
|
||||
}
|
||||
|
||||
// newSettingsResponse 将应用层动态设置键值转换为具名 HTTP 响应 DTO。
|
||||
func newSettingsResponse(values map[string]string) settingsResponse {
|
||||
// entries 保存待编码的设置项;顺序不影响兼容 JSON 对象,但便于测试和日志稳定。
|
||||
entries := make([]settingsEntryDTO, 0, len(values))
|
||||
// key 是当前设置名称;value 是对应的非敏感配置值。
|
||||
for key, value := range values {
|
||||
entries = append(entries, settingsEntryDTO{Key: key, Value: value})
|
||||
}
|
||||
return settingsResponse{Entries: entries}
|
||||
}
|
||||
|
||||
// MarshalJSON 保持设置接口原有的顶层键值对象契约,同时隐藏内部动态字段实现。
|
||||
func (response settingsResponse) MarshalJSON() ([]byte, error) {
|
||||
// values 保存兼容旧客户端的顶层设置对象。
|
||||
values := make(map[string]string, len(response.Entries))
|
||||
// entry 是当前待恢复为顶层设置字段的具名条目。
|
||||
for _, entry := range response.Entries {
|
||||
values[entry.Key] = entry.Value
|
||||
}
|
||||
return json.Marshal(values)
|
||||
}
|
||||
|
||||
// UnmarshalJSON 将旧客户端顶层设置对象解析为具名条目,供契约测试和边界适配使用。
|
||||
func (response *settingsResponse) UnmarshalJSON(data []byte) error {
|
||||
// values 保存收到的顶层设置对象;设置值均按字符串处理以避免秘密类型扩散。
|
||||
var values map[string]string
|
||||
// err 表示旧版顶层设置对象反序列化失败的原因。
|
||||
if err := json.Unmarshal(data, &values); err != nil {
|
||||
return err
|
||||
}
|
||||
*response = newSettingsResponse(values)
|
||||
return nil
|
||||
}
|
||||
|
||||
// qrLoginStatusResponse 是二维码状态的稳定响应 DTO,仅暴露非敏感状态和持久化结果。
|
||||
type qrLoginStatusResponse struct {
|
||||
// Success 表示当前扫码状态请求是否正常完成。
|
||||
Success bool `json:"success,omitempty"`
|
||||
// Status 是扫码会话当前状态。
|
||||
Status string `json:"status"`
|
||||
// Message 是可选的平台提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
// SessionID 是可选的扫码会话标识。
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
// AccountID 是扫码成功后创建或更新的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示扫码成功后是否新建本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
|
||||
// qrLoginVerificationResponse 是二维码风控验证完成的具名响应 DTO。
|
||||
type qrLoginVerificationResponse struct {
|
||||
// Success 表示验证结果是否成功。
|
||||
Success bool `json:"success"`
|
||||
// UNB 是平台账号标识。
|
||||
UNB string `json:"unb"`
|
||||
// AccountID 是持久化后的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示是否新建了本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,793 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
)
|
||||
|
||||
// aiReplySettingsResponse 是账号 AI 回复设置接口的具名响应 DTO。
|
||||
type aiReplySettingsResponse struct {
|
||||
// CookieID 是账号稳定标识;默认配置响应省略该字段。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// AIEnabled 表示账号 AI 回复是否启用。
|
||||
AIEnabled bool `json:"ai_enabled"`
|
||||
// MaxDiscountPercent 是允许的最大折扣比例。
|
||||
MaxDiscountPercent int `json:"max_discount_percent"`
|
||||
// MaxDiscountAmount 是允许的最大折扣金额。
|
||||
MaxDiscountAmount int `json:"max_discount_amount"`
|
||||
// MaxBargainRounds 是允许的最大砍价轮次。
|
||||
MaxBargainRounds int `json:"max_bargain_rounds"`
|
||||
// CustomPrompts 是账号自定义提示词。
|
||||
CustomPrompts string `json:"custom_prompts"`
|
||||
}
|
||||
|
||||
// aiModelsResponse 是 AI 模型发现接口的具名响应 DTO。
|
||||
type aiModelsResponse struct {
|
||||
// Models 是远端可用模型名称列表。
|
||||
Models []string `json:"models"`
|
||||
}
|
||||
|
||||
// userSettingResponse 是单个用户设置查询接口的具名响应 DTO。
|
||||
type userSettingResponse struct {
|
||||
// Value 是设置值文本。
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// cardResponse 是卡券详情和列表接口的具名响应 DTO。
|
||||
type cardResponse struct {
|
||||
// ID 是卡券组稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// Name 是卡券组名称。
|
||||
Name string `json:"name"`
|
||||
// Type 是卡券类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是 API 卡券配置 JSON。
|
||||
APIConfig string `json:"api_config"`
|
||||
// TextContent 是文本卡券内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是批量数据卡券内容。
|
||||
DataContent string `json:"data_content"`
|
||||
// ImageURL 是图片卡券地址。
|
||||
ImageURL string `json:"image_url"`
|
||||
// Description 是卡券组描述。
|
||||
Description string `json:"description"`
|
||||
// Enabled 表示卡券组是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// DelaySeconds 是自动发货延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
// IsMultiSpec 表示卡券组是否按规格区分。
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
// SpecName 是卡券规格名称。
|
||||
SpecName string `json:"spec_name"`
|
||||
// SpecValue 是卡券规格值。
|
||||
SpecValue string `json:"spec_value"`
|
||||
// UserID 是卡券所属用户标识,保留旧接口字段。
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// cardBatchResponse 是卡券批量创建接口的具名响应 DTO。
|
||||
type cardBatchResponse struct {
|
||||
// Success 表示批量解析和处理流程已完成。
|
||||
Success bool `json:"success"`
|
||||
// Total 是表格中解析出的数据行数量。
|
||||
Total int `json:"total"`
|
||||
// Created 是成功创建的卡券组数量。
|
||||
Created int `json:"created"`
|
||||
// Failed 是创建失败的数据行数量。
|
||||
Failed int `json:"failed"`
|
||||
// Rows 是逐行处理结果。
|
||||
Rows []cardBatchResultRow `json:"rows"`
|
||||
}
|
||||
|
||||
// cardAppendResponse 是追加卡密接口的具名响应 DTO。
|
||||
type cardAppendResponse struct {
|
||||
// Success 表示追加操作是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Added 是实际追加的卡密数量。
|
||||
Added int `json:"added"`
|
||||
}
|
||||
|
||||
// notificationChannelResponse 是通知渠道接口的具名响应 DTO。
|
||||
type notificationChannelResponse struct {
|
||||
// ID 是通知渠道稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// Name 是通知渠道名称。
|
||||
Name string `json:"name"`
|
||||
// Type 是通知渠道类型。
|
||||
Type string `json:"type"`
|
||||
// EventTypes 是订阅事件类型 JSON 或兼容分隔文本。
|
||||
EventTypes string `json:"event_types,omitempty"`
|
||||
// Enabled 表示通知渠道是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// UserID 是渠道所属用户标识,保留旧接口字段。
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newNotificationChannelResponse 将数据库通知渠道转换为 HTTP DTO。
|
||||
func newNotificationChannelResponse(channel notificationsapp.ChannelSummary) notificationChannelResponse {
|
||||
return notificationChannelResponse{
|
||||
ID: channel.ID, Name: channel.Name, Type: channel.Type,
|
||||
EventTypes: channel.EventTypes, Enabled: channel.Enabled, UserID: channel.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newNotificationChannelResponses 批量转换通知渠道,保持数据库模型不穿透 HTTP 层。
|
||||
func newNotificationChannelResponses(channels []notificationsapp.ChannelSummary) []notificationChannelResponse {
|
||||
// result 是转换后的通知渠道 DTO 列表。
|
||||
result := make([]notificationChannelResponse, 0, len(channels))
|
||||
// channel 是当前待转换的通知渠道数据库模型。
|
||||
for _, channel := range channels {
|
||||
result = append(result, newNotificationChannelResponse(channel))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// notificationBindingResponse 是单条账号通知绑定的具名 DTO。
|
||||
type notificationBindingResponse struct {
|
||||
// ID 是绑定记录稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ChannelID 是通知渠道标识。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// ChannelName 是通知渠道名称。
|
||||
ChannelName string `json:"channel_name"`
|
||||
// Enabled 表示该账号绑定是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// notificationBindingListResponse 是按账号分组的通知绑定响应 DTO。
|
||||
type notificationBindingListResponse map[string][]notificationBindingResponse
|
||||
|
||||
// accountBindingsResponse 是账号与通知渠道绑定查询接口的具名响应 DTO。
|
||||
type accountBindingsResponse struct {
|
||||
// CookieID 是账号稳定标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// ChannelIDs 是当前账号绑定的通知渠道标识列表。
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxItem 是不确定通知的非敏感运维摘要。
|
||||
// 该 DTO 不包含通知正文、渠道配置、凭证或最后错误原文。
|
||||
type notificationUncertainOutboxItem struct {
|
||||
// ID 是通知 outbox 记录的稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ChannelID 是关联通知渠道标识。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// OwnerUserID 是渠道所属用户标识,仅管理员查询时返回。
|
||||
OwnerUserID int64 `json:"owner_user_id,omitempty"`
|
||||
// EventType 是通知事件分类。
|
||||
EventType string `json:"event_type"`
|
||||
// AttemptCount 是进入不确定状态前的发送尝试次数。
|
||||
AttemptCount int `json:"attempt_count"`
|
||||
// UncertainAt 是进入不确定状态的 Unix 秒时间戳。
|
||||
UncertainAt int64 `json:"uncertain_at"`
|
||||
// HasError 表示是否存在本地确认错误,但不暴露错误原文。
|
||||
HasError bool `json:"has_error"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxResponse 是用户或管理员查询不确定通知的具名响应。
|
||||
type notificationUncertainOutboxResponse struct {
|
||||
// Total 是当前权限范围内的不确定通知总数。
|
||||
Total int `json:"total"`
|
||||
// Items 是按最近进入不确定状态排序的非敏感摘要列表。
|
||||
Items []notificationUncertainOutboxItem `json:"items"`
|
||||
}
|
||||
|
||||
// newNotificationUncertainOutboxResponse 将应用层不确定状态摘要转换为非敏感 HTTP DTO。
|
||||
// includeOwner 仅管理员列表使用,用于展示渠道所属用户但不改变正文脱敏边界。
|
||||
func newNotificationUncertainOutboxResponse(items []notificationsapp.UncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse {
|
||||
// result 保存不确定通知查询的具名响应。
|
||||
result := notificationUncertainOutboxResponse{Total: total, Items: make([]notificationUncertainOutboxItem, 0, len(items))}
|
||||
// item 保存当前待转换的应用层摘要。
|
||||
for _, item := range items {
|
||||
// responseItem 保存当前摘要对应的非敏感 API 行。
|
||||
responseItem := notificationUncertainOutboxItem{
|
||||
ID: item.ID, ChannelID: item.ChannelID, EventType: item.EventType,
|
||||
AttemptCount: item.AttemptCount, UncertainAt: item.UncertainAt, HasError: item.HasError,
|
||||
}
|
||||
if includeOwner {
|
||||
responseItem.OwnerUserID = item.OwnerUserID
|
||||
}
|
||||
result.Items = append(result.Items, responseItem)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// categoryRecommendationResponse 是商品类目推荐接口的具名响应 DTO。
|
||||
type categoryRecommendationResponse struct {
|
||||
// Success 表示类目推荐是否成功。
|
||||
Success bool `json:"success"`
|
||||
// Category 是推荐的商品类目。
|
||||
Category publishCategoryResponse `json:"category"`
|
||||
}
|
||||
|
||||
// publishCategoryResponse 是商品类目 HTTP 响应的稳定 DTO,不泄露平台包类型。
|
||||
type publishCategoryResponse struct {
|
||||
// CatID 是平台类目标识。
|
||||
CatID string `json:"cat_id"`
|
||||
// CatName 是平台类目名称。
|
||||
CatName string `json:"cat_name"`
|
||||
// ChannelCatID 是闲鱼频道类目标识。
|
||||
ChannelCatID string `json:"channel_cat_id,omitempty"`
|
||||
// TBCatID 是淘宝类目标识。
|
||||
TBCatID string `json:"tb_cat_id,omitempty"`
|
||||
}
|
||||
|
||||
// publishAutomationConfig 是批量发布预检与详情响应中的自动化配置 DTO。
|
||||
type publishAutomationConfig struct {
|
||||
// PaidDelivery 保存付款后自动发货配置。
|
||||
PaidDelivery publishCardAutomation `json:"paid_delivery"`
|
||||
// ReviewGift 保存评价后赠品配置。
|
||||
ReviewGift publishCardAutomation `json:"review_gift"`
|
||||
// ReviewRequest 保存超时求评价配置。
|
||||
ReviewRequest publishReviewRequestCfg `json:"review_request"`
|
||||
}
|
||||
|
||||
// publishCardAutomation 是批量发布中的卡密自动化 DTO。
|
||||
type publishCardAutomation struct {
|
||||
// Enabled 表示该自动化规则是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// Actions 保存按顺序执行的卡密动作。
|
||||
Actions []publishCardAction `json:"actions"`
|
||||
// ParseError 保存导入动作文本的解析错误。
|
||||
ParseError string `json:"-"`
|
||||
}
|
||||
|
||||
// publishCardAction 是单条批量卡密动作 DTO。
|
||||
type publishCardAction struct {
|
||||
// CardID 是卡密组标识。
|
||||
CardID int64 `json:"card_id"`
|
||||
// DeliveryCount 是每件商品发送的卡密数量。
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
// DelaySeconds 是发送动作的延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
// publishReviewRequestCfg 是批量发布求评价配置 DTO。
|
||||
type publishReviewRequestCfg struct {
|
||||
// Enabled 表示是否启用求评价。
|
||||
Enabled bool `json:"enabled"`
|
||||
// AfterShippedHours 是发货后的等待小时数。
|
||||
AfterShippedHours int `json:"after_shipped_hours"`
|
||||
// Message 是发送给买家的求评价文案。
|
||||
Message string `json:"message"`
|
||||
// MaxAttempts 是最多提醒次数。
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
// DelaySeconds 是提醒动作的延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
// itemPublishBatchPreviewResponse 是商品批量发布预检接口的具名响应 DTO。
|
||||
type itemPublishBatchPreviewResponse struct {
|
||||
// Success 表示预检是否完成。
|
||||
Success bool `json:"success"`
|
||||
// PreviewID 是后续启动批量发布使用的预检批次标识。
|
||||
PreviewID string `json:"preview_id"`
|
||||
// Total 是预检数据行总数。
|
||||
Total int `json:"total"`
|
||||
// Valid 是通过预检的数据行数量。
|
||||
Valid int `json:"valid"`
|
||||
// Invalid 是未通过预检的数据行数量。
|
||||
Invalid int `json:"invalid"`
|
||||
// Rows 是逐行预检结果。
|
||||
Rows []publishBatchPreviewRow `json:"rows"`
|
||||
}
|
||||
|
||||
// batchIDResponse 是商品批量任务启动或重试接口的具名响应 DTO。
|
||||
type batchIDResponse struct {
|
||||
// Success 表示任务操作是否完成。
|
||||
Success bool `json:"success"`
|
||||
// BatchID 是商品批量任务标识。
|
||||
BatchID string `json:"batch_id"`
|
||||
}
|
||||
|
||||
// batchCancelResponse 是商品批量任务取消接口的具名响应 DTO。
|
||||
type batchCancelResponse struct {
|
||||
// Success 表示取消请求是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Status 是任务取消后的状态。
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// itemPublishBatchRowResponse 是商品批量任务逐行详情 DTO。
|
||||
type itemPublishBatchRowResponse struct {
|
||||
// ID 是批量任务明细行主键。
|
||||
ID int64 `json:"id"`
|
||||
// RowNo 是导入表格中的行号。
|
||||
RowNo int `json:"row_no"`
|
||||
// CookieID 是商品发布目标账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// Title 是商品标题。
|
||||
Title string `json:"title"`
|
||||
// Price 是商品价格文本。
|
||||
Price string `json:"price"`
|
||||
// Quantity 是商品库存数量。
|
||||
Quantity int `json:"quantity"`
|
||||
// Images 是商品图片引用列表。
|
||||
Images []string `json:"images"`
|
||||
// Category 是商品发布类目。
|
||||
Category publishCategoryResponse `json:"category"`
|
||||
// Automation 是发布后自动化配置。
|
||||
Automation publishAutomationConfig `json:"automation"`
|
||||
// Status 是当前明细行状态。
|
||||
Status string `json:"status"`
|
||||
// ItemID 是发布成功后的平台商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemURL 是发布成功后的商品地址。
|
||||
ItemURL string `json:"item_url"`
|
||||
// ErrorMessage 是明细行失败原因。
|
||||
ErrorMessage string `json:"error_message"`
|
||||
// FailureKind 是失败类型。
|
||||
FailureKind string `json:"failure_kind"`
|
||||
}
|
||||
|
||||
// itemPublishBatchResponse 是商品批量任务详情接口的具名响应 DTO。
|
||||
type itemPublishBatchResponse struct {
|
||||
// ID 是商品批量任务标识。
|
||||
ID string `json:"id"`
|
||||
// Status 是批量任务状态。
|
||||
Status string `json:"status"`
|
||||
// Filename 是原始上传文件名。
|
||||
Filename string `json:"filename"`
|
||||
// Total 是明细行总数。
|
||||
Total int `json:"total"`
|
||||
// Success 是成功发布的明细行数量,保留旧字段名称。
|
||||
Success int `json:"success"`
|
||||
// Failed 是失败明细行数量。
|
||||
Failed int `json:"failed"`
|
||||
// Pending 是待处理明细行数量。
|
||||
Pending int `json:"pending"`
|
||||
// Running 是正在处理明细行数量。
|
||||
Running int `json:"running"`
|
||||
// Retryable 是可重试明细行数量。
|
||||
Retryable int `json:"retryable"`
|
||||
// Rows 是批量任务逐行结果。
|
||||
Rows []itemPublishBatchRowResponse `json:"rows"`
|
||||
// Location 是批次统一发货地对象。
|
||||
Location any `json:"location"`
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int `json:"publish_interval_seconds"`
|
||||
// CreatedAt 是任务创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// UpdatedAt 是任务更新时间。
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// itemPublishBatchListResponse 是商品批量任务列表接口的具名响应 DTO。
|
||||
type itemPublishBatchListResponse struct {
|
||||
// Batches 是当前用户的商品批量任务列表。
|
||||
Batches []itemPublishBatchResponse `json:"batches"`
|
||||
}
|
||||
|
||||
// keywordBasicResponse 是传统关键词接口的基础响应 DTO。
|
||||
type keywordBasicResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
}
|
||||
|
||||
// keywordItemResponse 是带商品范围的关键词响应 DTO。
|
||||
type keywordItemResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
}
|
||||
|
||||
// keywordTypedResponse 是支持文本/图片类型的关键词响应 DTO。
|
||||
type keywordTypedResponse struct {
|
||||
// ID 是关键词规则主键。
|
||||
ID int64 `json:"id"`
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// Type 是回复类型。
|
||||
Type string `json:"type"`
|
||||
// ImageURL 是图片回复地址。
|
||||
ImageURL string `json:"image_url"`
|
||||
}
|
||||
|
||||
// itemReplyResponse 是指定商品回复接口的具名 DTO。
|
||||
type itemReplyResponse struct {
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
// CookieID 是账号稳定标识。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// ReplyContent 是指定商品的回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
}
|
||||
|
||||
// defaultReplyResponse 是默认回复接口的具名 DTO。
|
||||
type defaultReplyResponse struct {
|
||||
// CookieID 是账号稳定标识;单账号查询响应可以省略。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// Enabled 表示默认回复是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// ReplyContent 是默认文字回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
// ReplyImageURL 是默认图片回复地址。
|
||||
ReplyImageURL string `json:"reply_image_url,omitempty"`
|
||||
// ReplyOnce 表示是否只回复一次。
|
||||
ReplyOnce bool `json:"reply_once"`
|
||||
}
|
||||
|
||||
// newDefaultReplyResponse 将默认回复应用模型转换为 HTTP DTO。
|
||||
func newDefaultReplyResponse(cookieID string, reply defaultreplyapp.Reply) defaultReplyResponse {
|
||||
return defaultReplyResponse{
|
||||
CookieID: cookieID, Enabled: reply.Enabled, ReplyContent: reply.ReplyContent,
|
||||
ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce,
|
||||
}
|
||||
}
|
||||
|
||||
// accountTaskSettingsResponse 是账号任务设置接口的具名 DTO。
|
||||
type accountTaskSettingsResponse struct {
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// AutoRateEnabled 表示自动评价是否启用。
|
||||
AutoRateEnabled bool `json:"auto_rate_enabled"`
|
||||
// RateContent 是自动评价文案。
|
||||
RateContent string `json:"rate_content"`
|
||||
// AutoPolishEnabled 表示自动擦亮是否启用。
|
||||
AutoPolishEnabled bool `json:"auto_polish_enabled"`
|
||||
// PolishTime 是自动擦亮本地时间。
|
||||
PolishTime string `json:"polish_time"`
|
||||
// LastRateScanAt 是最近一次评价扫描时间。
|
||||
LastRateScanAt int64 `json:"last_rate_scan_at"`
|
||||
// LastPolishDate 是最近一次擦亮日期。
|
||||
LastPolishDate string `json:"last_polish_date"`
|
||||
// LastPolishAt 是最近一次擦亮时间。
|
||||
LastPolishAt int64 `json:"last_polish_at"`
|
||||
}
|
||||
|
||||
// accountTaskRunResponse 是账号任务执行记录的具名 DTO。
|
||||
type accountTaskRunResponse struct {
|
||||
// ID 是任务执行记录主键。
|
||||
ID int64 `json:"id"`
|
||||
// RunKey 是任务幂等键。
|
||||
RunKey string `json:"run_key"`
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// TargetID 是任务目标标识。
|
||||
TargetID string `json:"target_id"`
|
||||
// RunDate 是任务业务日期。
|
||||
RunDate string `json:"run_date"`
|
||||
// Status 是任务执行状态。
|
||||
Status string `json:"status"`
|
||||
// SuccessCount 是任务成功数量。
|
||||
SuccessCount int `json:"success_count"`
|
||||
// FailedCount 是任务失败数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// ErrorMessage 是任务失败说明。
|
||||
ErrorMessage string `json:"error_message"`
|
||||
// NextRetryAt 是下一次重试时间。
|
||||
NextRetryAt int64 `json:"next_retry_at"`
|
||||
// StartedAt 是任务开始时间。
|
||||
StartedAt int64 `json:"started_at"`
|
||||
// FinishedAt 是任务完成时间。
|
||||
FinishedAt int64 `json:"finished_at"`
|
||||
}
|
||||
|
||||
// accountTaskSummaryResponse 是手动执行账号任务的统计 DTO。
|
||||
type accountTaskSummaryResponse struct {
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// Found 是发现的目标数量。
|
||||
Found int `json:"found"`
|
||||
// Success 是成功处理数量。
|
||||
Success int `json:"success"`
|
||||
// Failed 是失败处理数量。
|
||||
Failed int `json:"failed"`
|
||||
// Skipped 是跳过数量。
|
||||
Skipped int `json:"skipped"`
|
||||
// Message 是任务结果说明。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// accountTaskRunResponseEnvelope 是手动执行账号任务的具名响应 DTO。
|
||||
type accountTaskRunResponseEnvelope struct {
|
||||
// Success 表示任务请求是否成功完成。
|
||||
Success bool `json:"success"`
|
||||
// Summary 是账号任务执行统计。
|
||||
Summary accountTaskSummaryResponse `json:"summary"`
|
||||
}
|
||||
|
||||
// accountTaskRunsResponse 是账号任务执行记录列表的具名响应 DTO。
|
||||
type accountTaskRunsResponse struct {
|
||||
// Runs 是当前账号最近的任务执行记录。
|
||||
Runs []accountTaskRunResponse `json:"runs"`
|
||||
}
|
||||
|
||||
// adminUserResponse 是管理员用户列表项的具名响应 DTO。
|
||||
type adminUserResponse struct {
|
||||
// ID 是用户主键。
|
||||
ID int64 `json:"id"`
|
||||
// Username 是用户登录名。
|
||||
Username string `json:"username"`
|
||||
// Email 是用户邮箱。
|
||||
Email string `json:"email"`
|
||||
// IsActive 表示用户是否启用。
|
||||
IsActive bool `json:"is_active"`
|
||||
// IsAdmin 表示用户是否为管理员。
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
// CreatedAt 是用户创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// CookieCount 是用户拥有的账号数量。
|
||||
CookieCount int `json:"cookie_count"`
|
||||
}
|
||||
|
||||
// adminCookieResponse 是管理员账号列表项的具名响应 DTO。
|
||||
type adminCookieResponse struct {
|
||||
// ID 是账号稳定标识。
|
||||
ID string `json:"id"`
|
||||
// UserID 是账号所属用户主键。
|
||||
UserID int64 `json:"user_id"`
|
||||
// Remark 是账号备注。
|
||||
Remark string `json:"remark"`
|
||||
// CreatedAt 是账号创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// Owner 是账号所属用户名。
|
||||
Owner string `json:"owner"`
|
||||
// Enabled 表示账号是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// adminStatsResponse 是管理员全局统计的具名响应 DTO。
|
||||
type adminStatsResponse struct {
|
||||
// TotalUsers 是用户总数。
|
||||
TotalUsers int64 `json:"total_users"`
|
||||
// TotalCookies 是账号总数。
|
||||
TotalCookies int64 `json:"total_cookies"`
|
||||
// ActiveCookies 是活跃账号数。
|
||||
ActiveCookies int64 `json:"active_cookies"`
|
||||
// TotalCards 是卡券总数。
|
||||
TotalCards int64 `json:"total_cards"`
|
||||
// TotalKeywords 是关键词规则总数。
|
||||
TotalKeywords int64 `json:"total_keywords"`
|
||||
// TotalOrders 是有效订单总数。
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
}
|
||||
|
||||
// dashboardStatsResponse 是当前用户数据概览的具名响应 DTO。
|
||||
type dashboardStatsResponse struct {
|
||||
// TotalCookies 是账号总数。
|
||||
TotalCookies int64 `json:"total_cookies"`
|
||||
// ActiveCookies 是活跃账号数。
|
||||
ActiveCookies int64 `json:"active_cookies"`
|
||||
// TotalCards 是卡券总数。
|
||||
TotalCards int64 `json:"total_cards"`
|
||||
// AvailableCardStock 是可用卡券库存数量。
|
||||
AvailableCardStock int64 `json:"available_card_stock"`
|
||||
// TotalKeywords 是关键词规则总数。
|
||||
TotalKeywords int64 `json:"total_keywords"`
|
||||
// TotalOrders 是订单总数。
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
}
|
||||
|
||||
// analyticsRevenueStatsResponse 是订单收益统计的具名 DTO。
|
||||
type analyticsRevenueStatsResponse struct {
|
||||
// TotalOrders 是统计范围内的订单数。
|
||||
TotalOrders int `json:"total_orders"`
|
||||
// TotalAmount 是统计范围内的订单总金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
// AvgAmount 是订单平均金额。
|
||||
AvgAmount float64 `json:"avg_amount"`
|
||||
// UniqueBuyers 是买家数量。
|
||||
UniqueBuyers int `json:"unique_buyers"`
|
||||
// UniqueItems 是商品数量。
|
||||
UniqueItems int `json:"unique_items"`
|
||||
}
|
||||
|
||||
// analyticsDailyStatsResponse 是按日期聚合的订单统计 DTO。
|
||||
type analyticsDailyStatsResponse struct {
|
||||
// Date 是用户本地日期。
|
||||
Date string `json:"date"`
|
||||
// OrderCount 是当天订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// Amount 是当天订单金额。
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
// analyticsStatusStatsResponse 是按订单状态聚合的统计 DTO。
|
||||
type analyticsStatusStatsResponse struct {
|
||||
// Status 是归一化后的订单状态。
|
||||
Status string `json:"status"`
|
||||
// Count 是该状态订单数。
|
||||
Count int `json:"count"`
|
||||
// Amount 是该状态订单金额。
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
// analyticsCityStatsResponse 是按收货城市聚合的统计 DTO。
|
||||
type analyticsCityStatsResponse struct {
|
||||
// City 是收货城市。
|
||||
City string `json:"city"`
|
||||
// OrderCount 是该城市订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// TotalAmount 是该城市订单金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
}
|
||||
|
||||
// analyticsItemStatsResponse 是按商品聚合的统计 DTO。
|
||||
type analyticsItemStatsResponse struct {
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// OrderCount 是该商品订单数。
|
||||
OrderCount int `json:"order_count"`
|
||||
// TotalAmount 是该商品订单金额。
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
// AvgAmount 是该商品订单平均金额。
|
||||
AvgAmount float64 `json:"avg_amount"`
|
||||
}
|
||||
|
||||
// orderAnalyticsResponse 是订单分析接口的具名响应 DTO。
|
||||
type orderAnalyticsResponse struct {
|
||||
// RevenueStats 是收益统计。
|
||||
RevenueStats analyticsRevenueStatsResponse `json:"revenue_stats"`
|
||||
// DailyStats 是按日统计。
|
||||
DailyStats []analyticsDailyStatsResponse `json:"daily_stats"`
|
||||
// StatusStats 是按状态统计。
|
||||
StatusStats []analyticsStatusStatsResponse `json:"status_stats"`
|
||||
// CityStats 是按城市统计。
|
||||
CityStats []analyticsCityStatsResponse `json:"city_stats"`
|
||||
// ItemStats 是按商品统计。
|
||||
ItemStats []analyticsItemStatsResponse `json:"item_stats"`
|
||||
}
|
||||
|
||||
// validOrderResponse 是有效订单明细项的具名响应 DTO。
|
||||
type validOrderResponse struct {
|
||||
// OrderID 是平台订单标识。
|
||||
OrderID string `json:"order_id"`
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string `json:"buyer_id"`
|
||||
// ItemTitle 是商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemImage 是商品图片地址。
|
||||
ItemImage string `json:"item_image"`
|
||||
// Quantity 是订单数量文本。
|
||||
Quantity string `json:"quantity"`
|
||||
// Amount 是订单金额文本。
|
||||
Amount string `json:"amount"`
|
||||
// OrderStatus 是兼容保留的订单状态字段。
|
||||
OrderStatus string `json:"order_status"`
|
||||
// Status 是归一化后的订单状态。
|
||||
Status string `json:"status"`
|
||||
// CookieID 是订单所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// CreatedAt 是订单创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// validOrdersResponse 是有效订单分页查询的具名响应 DTO。
|
||||
type validOrdersResponse struct {
|
||||
// Orders 是当前页有效订单。
|
||||
Orders []validOrderResponse `json:"orders"`
|
||||
// Total 是符合条件的订单总数。
|
||||
Total int `json:"total"`
|
||||
// Page 是当前页码。
|
||||
Page int `json:"page"`
|
||||
// PageSize 是当前页大小。
|
||||
PageSize int `json:"page_size"`
|
||||
// Truncated 表示是否还有未返回的订单。
|
||||
Truncated bool `json:"truncated"`
|
||||
}
|
||||
|
||||
// qrLoginGenerateResponse 是扫码登录二维码生成的具名响应 DTO。
|
||||
type qrLoginGenerateResponse struct {
|
||||
// Success 表示二维码是否生成成功。
|
||||
Success bool `json:"success"`
|
||||
// SessionID 是扫码登录会话标识。
|
||||
SessionID string `json:"session_id"`
|
||||
// QRCodeURL 是二维码图片地址。
|
||||
QRCodeURL string `json:"qr_code_url"`
|
||||
// Message 是可选的提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// settingsEntryDTO 是单条设置键值的具名 DTO;仅在 HTTP 边界内部用于稳定排序和校验。
|
||||
type settingsEntryDTO struct {
|
||||
// Key 是设置项的稳定键名。
|
||||
Key string `json:"key"`
|
||||
// Value 是设置项的脱敏文本值。
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// settingsResponse 是设置查询的具名响应 DTO;序列化时保持旧客户端的顶层键值对象形状。
|
||||
type settingsResponse struct {
|
||||
// Entries 保存设置键值,避免 DTO 直接暴露动态 map 字段。
|
||||
Entries []settingsEntryDTO `json:"-"`
|
||||
}
|
||||
|
||||
// newSettingsResponse 将应用层动态设置键值转换为具名 HTTP 响应 DTO。
|
||||
func newSettingsResponse(values map[string]string) settingsResponse {
|
||||
// entries 保存待编码的设置项;顺序不影响兼容 JSON 对象,但便于测试和日志稳定。
|
||||
entries := make([]settingsEntryDTO, 0, len(values))
|
||||
// key 是当前设置名称;value 是对应的非敏感配置值。
|
||||
for key, value := range values {
|
||||
entries = append(entries, settingsEntryDTO{Key: key, Value: value})
|
||||
}
|
||||
return settingsResponse{Entries: entries}
|
||||
}
|
||||
|
||||
// MarshalJSON 保持设置接口原有的顶层键值对象契约,同时隐藏内部动态字段实现。
|
||||
func (response settingsResponse) MarshalJSON() ([]byte, error) {
|
||||
// values 保存兼容旧客户端的顶层设置对象。
|
||||
values := make(map[string]string, len(response.Entries))
|
||||
// entry 是当前待恢复为顶层设置字段的具名条目。
|
||||
for _, entry := range response.Entries {
|
||||
values[entry.Key] = entry.Value
|
||||
}
|
||||
return json.Marshal(values)
|
||||
}
|
||||
|
||||
// UnmarshalJSON 将旧客户端顶层设置对象解析为具名条目,供契约测试和边界适配使用。
|
||||
func (response *settingsResponse) UnmarshalJSON(data []byte) error {
|
||||
// values 保存收到的顶层设置对象;设置值均按字符串处理以避免秘密类型扩散。
|
||||
var values map[string]string
|
||||
// err 表示旧版顶层设置对象反序列化失败的原因。
|
||||
if err := json.Unmarshal(data, &values); err != nil {
|
||||
return err
|
||||
}
|
||||
*response = newSettingsResponse(values)
|
||||
return nil
|
||||
}
|
||||
|
||||
// qrLoginStatusResponse 是二维码状态的稳定响应 DTO,仅暴露非敏感状态和持久化结果。
|
||||
type qrLoginStatusResponse struct {
|
||||
// Success 表示当前扫码状态请求是否正常完成。
|
||||
Success bool `json:"success,omitempty"`
|
||||
// Status 是扫码会话当前状态。
|
||||
Status string `json:"status"`
|
||||
// Message 是可选的平台提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
// SessionID 是可选的扫码会话标识。
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
// AccountID 是扫码成功后创建或更新的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示扫码成功后是否新建本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
|
||||
// qrLoginVerificationResponse 是二维码风控验证完成的具名响应 DTO。
|
||||
type qrLoginVerificationResponse struct {
|
||||
// Success 表示验证结果是否成功。
|
||||
Success bool `json:"success"`
|
||||
// UNB 是平台账号标识。
|
||||
UNB string `json:"unb"`
|
||||
// AccountID 是持久化后的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示是否新建了本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
@@ -698,77 +698,6 @@ func postageDTO(req PublishItemRequest) map[string]any {
|
||||
return out
|
||||
}
|
||||
|
||||
// publishLabels 封装发布Labels业务协调。
|
||||
func publishLabels(category map[string]any) []any {
|
||||
// cards 用于本次流程后续判断的卡密列表
|
||||
cards, _ := category["cardList"].([]any)
|
||||
// out 用于本次流程后续判断的out
|
||||
out := []any{}
|
||||
// rawCard 表示当前遍历过程中的原始卡密
|
||||
for _, rawCard := range cards {
|
||||
// card 用于本次流程后续判断的卡密
|
||||
card := mapFromAny(rawCard)
|
||||
// cardData 用于本次流程后续判断的卡密数据
|
||||
cardData := mapFromAny(card["cardData"])
|
||||
if cardData == nil {
|
||||
continue
|
||||
}
|
||||
// values 用于本次流程后续判断的values
|
||||
values, _ := cardData["valuesList"].([]any)
|
||||
// rawValue 表示当前遍历过程中的原始值
|
||||
for _, rawValue := range values {
|
||||
// value 用于本次流程后续判断的值
|
||||
value := mapFromAny(rawValue)
|
||||
if !publishLabelSelected(value["isClicked"]) {
|
||||
continue
|
||||
}
|
||||
// propertyID 用于本次流程后续判断的propertyID
|
||||
propertyID := mtopString(cardData["propertyId"])
|
||||
// propertyName 用于本次流程后续判断的property名称
|
||||
propertyName := mtopString(cardData["propertyName"])
|
||||
// channelCatID 用于本次流程后续判断的渠道CatID
|
||||
channelCatID := mtopString(value["channelCatId"])
|
||||
// catName 用于本次流程后续判断的cat名称
|
||||
catName := mtopString(value["catName"])
|
||||
out = append(out, map[string]any{
|
||||
"channelCateName": catName,
|
||||
"valueId": nil,
|
||||
"channelCateId": channelCatID,
|
||||
"valueName": nil,
|
||||
"tbCatId": mtopString(value["tbCatId"]),
|
||||
"subPropertyId": nil,
|
||||
"labelType": "common",
|
||||
"subValueId": nil,
|
||||
"labelId": nil,
|
||||
"propertyName": propertyName,
|
||||
"isUserClick": "1",
|
||||
"isUserCancel": nil,
|
||||
"from": "newPublishChoice",
|
||||
"propertyId": propertyID,
|
||||
"labelFrom": "newPublish",
|
||||
"text": catName,
|
||||
"properties": propertyID + "##" + propertyName + ":" + channelCatID + "##" + catName,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// publishLabelSelected 封装发布LabelSelected业务协调。
|
||||
func publishLabelSelected(value any) bool {
|
||||
if // selected、ok 用于本次流程后续判断的selected、ok
|
||||
selected, ok := value.(bool); ok {
|
||||
return selected
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(mtopString(value))) {
|
||||
case "1", "true":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// classifyPublishError 封装classify发布错误业务协调。
|
||||
func classifyPublishError(ret []string, decoded map[string]any) error {
|
||||
// bodyBytes 用于本次流程后续判断的请求体Bytes
|
||||
@@ -837,51 +766,6 @@ func parsePix(pix string) (int, int) {
|
||||
return w, h
|
||||
}
|
||||
|
||||
// findStringDeep 封装findStringDeep业务协调。
|
||||
func findStringDeep(v any, keys ...string) string {
|
||||
// keySet 用于本次流程后续判断的keySet
|
||||
keySet := map[string]struct{}{}
|
||||
// k 表示当前遍历过程中的k
|
||||
for _, k := range keys {
|
||||
keySet[k] = struct{}{}
|
||||
}
|
||||
// walk 用于本次流程后续判断的walk
|
||||
var walk func(any) string
|
||||
walk = func(cur any) string {
|
||||
switch // x 用于本次流程后续判断的x
|
||||
x := cur.(type) {
|
||||
case map[string]any:
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range x {
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := keySet[k]; ok {
|
||||
if // s 用于本次流程后续判断的s
|
||||
s := mtopString(v); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
// v 表示当前遍历过程中的v
|
||||
for _, v := range x {
|
||||
if // s 用于本次流程后续判断的s
|
||||
s := walk(v); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// v 表示当前遍历过程中的v
|
||||
for _, v := range x {
|
||||
if // s 用于本次流程后续判断的s
|
||||
s := walk(v); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(v)
|
||||
}
|
||||
|
||||
// centsText 封装cents文本业务协调。
|
||||
func centsText(cents int64) string {
|
||||
return strconv.FormatFloat(float64(cents)/100, 'f', 2, 64)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package mtop
|
||||
|
||||
import "strings"
|
||||
|
||||
// publishLabels 将推荐类目中的用户选择转换为最终发布请求标签。
|
||||
func publishLabels(category map[string]any) []any {
|
||||
// cards 保存推荐响应的属性卡片集合。
|
||||
cards, _ := category["cardList"].([]any)
|
||||
// out 保存所有已选属性对应的发布标签。
|
||||
out := []any{}
|
||||
// rawCard 是当前待处理的属性卡片原始结构。
|
||||
for _, rawCard := range cards {
|
||||
// cardData 是当前属性卡片的嵌套配置。
|
||||
cardData := mapFromAny(mapFromAny(rawCard)["cardData"])
|
||||
if cardData == nil {
|
||||
continue
|
||||
}
|
||||
// rawValue 是当前属性候选值。
|
||||
for _, rawValue := range cardData["valuesList"].([]any) {
|
||||
// value 是标准化后的候选属性值。
|
||||
value := mapFromAny(rawValue)
|
||||
if !publishLabelSelected(value["isClicked"]) {
|
||||
continue
|
||||
}
|
||||
// propertyID、propertyName 分别是当前属性的稳定平台标识和展示名称。
|
||||
propertyID, propertyName := mtopString(cardData["propertyId"]), mtopString(cardData["propertyName"])
|
||||
// channelCatID、catName 分别是已选类目值的频道标识和展示名称。
|
||||
channelCatID, catName := mtopString(value["channelCatId"]), mtopString(value["catName"])
|
||||
out = append(out, map[string]any{"channelCateName": catName, "valueId": nil, "channelCateId": channelCatID, "valueName": nil, "tbCatId": mtopString(value["tbCatId"]), "subPropertyId": nil, "labelType": "common", "subValueId": nil, "labelId": nil, "propertyName": propertyName, "isUserClick": "1", "isUserCancel": nil, "from": "newPublishChoice", "propertyId": propertyID, "labelFrom": "newPublish", "text": catName, "properties": propertyID + "##" + propertyName + ":" + channelCatID + "##" + catName})
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// publishLabelSelected 判断平台值是否以布尔或文本真值形式被选中。
|
||||
func publishLabelSelected(value any) bool {
|
||||
// selected、ok 分别是 value 是否为布尔类型及其实际真值。
|
||||
if selected, ok := value.(bool); ok {
|
||||
return selected
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(mtopString(value)), "1") || strings.EqualFold(strings.TrimSpace(mtopString(value)), "true")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package mtop
|
||||
|
||||
// findStringDeep 在嵌套发布响应中按优先键集提取首个非空字符串。
|
||||
func findStringDeep(value any, keys ...string) string {
|
||||
// keySet 保存需要优先匹配的响应字段名。
|
||||
keySet := map[string]struct{}{}
|
||||
// key 是当前待登记的响应字段名。
|
||||
for _, key := range keys {
|
||||
keySet[key] = struct{}{}
|
||||
}
|
||||
// walk 递归遍历 map 和数组,优先读取当前 map 的目标字段。
|
||||
var walk func(any) string
|
||||
walk = func(current any) string {
|
||||
// typed 是当前递归节点断言后的响应容器类型。
|
||||
switch typed := current.(type) {
|
||||
case map[string]any:
|
||||
// key、nested 分别是当前响应对象的字段名和字段值。
|
||||
for key, nested := range typed {
|
||||
// wanted 表示当前字段是否属于调用方要求优先读取的键集。
|
||||
if _, wanted := keySet[key]; wanted {
|
||||
// text 是当前目标字段规范化后的非空文本。
|
||||
if text := mtopString(nested); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
// nested 是当前对象中待递归查询的非目标字段值。
|
||||
for _, nested := range typed {
|
||||
// text 是子树递归返回的首个非空文本。
|
||||
if text := walk(nested); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// nested 是当前数组中待递归查询的元素。
|
||||
for _, nested := range typed {
|
||||
// text 是子元素递归返回的首个非空文本。
|
||||
if text := walk(nested); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
+104
-137
@@ -87,147 +87,114 @@ func (d *msgpackDecoder) decodeTypedValue(fb byte) (any, error) {
|
||||
return false, nil
|
||||
case 0xc3:
|
||||
return true, nil
|
||||
case 0xc4: // bin 8
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := d.readByte()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readBytes(int(n))
|
||||
case 0xc5: // bin 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readBytes(int(binary.BigEndian.Uint16(b)))
|
||||
case 0xc6: // bin 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readBytes(int(binary.BigEndian.Uint32(b)))
|
||||
case 0xca: // float 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// bits 用于本次流程后续判断的bits
|
||||
bits := binary.BigEndian.Uint32(b)
|
||||
return float64(math.Float32frombits(bits)), nil
|
||||
case 0xcb: // float 64
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return math.Float64frombits(binary.BigEndian.Uint64(b)), nil
|
||||
case 0xcc: // uint 8
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := d.readByte()
|
||||
return uint64(n), err
|
||||
case 0xcd: // uint 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return uint64(binary.BigEndian.Uint16(b)), nil
|
||||
case 0xce: // uint 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return uint64(binary.BigEndian.Uint32(b)), nil
|
||||
case 0xcf: // uint 64
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return binary.BigEndian.Uint64(b), nil
|
||||
case 0xd0: // int 8
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := d.readByte()
|
||||
// #nosec G115 -- MessagePack 有符号整数使用二进制补码编码,此转换用于符号扩展。
|
||||
return int64(int8(n)), err
|
||||
case 0xd1: // int 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(int16(binary.BigEndian.Uint16(b))), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd2: // int 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(int32(binary.BigEndian.Uint32(b))), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd3: // int 64
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return int64(binary.BigEndian.Uint64(b)), nil // #nosec G115 -- 协议要求的符号扩展
|
||||
case 0xd9: // str 8
|
||||
// n、err 用于本次流程后续判断的n、err
|
||||
n, err := d.readByte()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readString(int(n))
|
||||
case 0xda: // str 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readString(int(binary.BigEndian.Uint16(b)))
|
||||
case 0xdb: // str 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readString(int(binary.BigEndian.Uint32(b)))
|
||||
case 0xdc: // array 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.decodeArray(int(binary.BigEndian.Uint16(b)))
|
||||
case 0xdd: // array 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.decodeArray(int(binary.BigEndian.Uint32(b)))
|
||||
case 0xde: // map 16
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.decodeMap(int(binary.BigEndian.Uint16(b)))
|
||||
case 0xdf: // map 32
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := d.readBytes(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.decodeMap(int(binary.BigEndian.Uint32(b)))
|
||||
case 0xc4, 0xc5, 0xc6:
|
||||
return d.decodeBinary(fb)
|
||||
case 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3:
|
||||
return d.decodeNumber(fb)
|
||||
case 0xd9, 0xda, 0xdb:
|
||||
return d.decodeLongString(fb)
|
||||
case 0xdc, 0xdd, 0xde, 0xdf:
|
||||
return d.decodeCollection(fb)
|
||||
}
|
||||
return nil, fmt.Errorf("msgpack: unknown format byte 0x%02x", fb)
|
||||
}
|
||||
|
||||
// decodeBinary 解码带长度前缀的二进制值。
|
||||
func (d *msgpackDecoder) decodeBinary(fb byte) (any, error) {
|
||||
// width 是当前二进制长度字段的字节数。
|
||||
width := map[byte]int{0xc4: 1, 0xc5: 2, 0xc6: 4}[fb]
|
||||
// length、err 保存二进制载荷长度及读取错误。
|
||||
length, err := d.readLength(width)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.readBytes(length)
|
||||
}
|
||||
|
||||
// decodeNumber 解码浮点数、无符号整数和有符号整数。
|
||||
func (d *msgpackDecoder) decodeNumber(fb byte) (any, error) {
|
||||
// width 是当前数值载荷的字节数。
|
||||
width := map[byte]int{0xca: 4, 0xcb: 8, 0xcc: 1, 0xcd: 2, 0xce: 4, 0xcf: 8, 0xd0: 1, 0xd1: 2, 0xd2: 4, 0xd3: 8}[fb]
|
||||
// data、err 保存原始数值载荷及读取错误。
|
||||
data, err := d.readBytes(width)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch fb {
|
||||
case 0xca:
|
||||
return float64(math.Float32frombits(binary.BigEndian.Uint32(data))), nil
|
||||
case 0xcb:
|
||||
return math.Float64frombits(binary.BigEndian.Uint64(data)), nil
|
||||
case 0xcc:
|
||||
return uint64(data[0]), nil
|
||||
case 0xcd:
|
||||
return uint64(binary.BigEndian.Uint16(data)), nil
|
||||
case 0xce:
|
||||
return uint64(binary.BigEndian.Uint32(data)), nil
|
||||
case 0xcf:
|
||||
return binary.BigEndian.Uint64(data), nil
|
||||
case 0xd0:
|
||||
return int64(int8(data[0])), nil // #nosec G115 -- MessagePack 二进制补码符号扩展。
|
||||
case 0xd1:
|
||||
return int64(int16(binary.BigEndian.Uint16(data))), nil // #nosec G115 -- MessagePack 二进制补码符号扩展。
|
||||
case 0xd2:
|
||||
return int64(int32(binary.BigEndian.Uint32(data))), nil // #nosec G115 -- MessagePack 二进制补码符号扩展。
|
||||
default:
|
||||
return int64(binary.BigEndian.Uint64(data)), nil // #nosec G115 -- MessagePack 二进制补码符号扩展。
|
||||
}
|
||||
}
|
||||
|
||||
// decodeLongString 解码带长度前缀的字符串。
|
||||
func (d *msgpackDecoder) decodeLongString(fb byte) (any, error) {
|
||||
return d.decodeSized(fb, func(length int) (any, error) {
|
||||
return d.readString(length)
|
||||
})
|
||||
}
|
||||
|
||||
// decodeCollection 解码带长度前缀的数组或 map。
|
||||
func (d *msgpackDecoder) decodeCollection(fb byte) (any, error) {
|
||||
return d.decodeSized(fb, func(length int) (any, error) {
|
||||
if fb == 0xdc || fb == 0xdd {
|
||||
return d.decodeArray(length)
|
||||
}
|
||||
return d.decodeMap(length)
|
||||
})
|
||||
}
|
||||
|
||||
// decodeSized 按格式码读取长度并交给对应的载荷解码函数。
|
||||
func (d *msgpackDecoder) decodeSized(fb byte, decode func(int) (any, error)) (any, error) {
|
||||
// width 是当前格式码对应的长度前缀字节数。
|
||||
width := 1
|
||||
if fb == 0xda || fb == 0xdc || fb == 0xde {
|
||||
width = 2
|
||||
} else if fb != 0xd9 {
|
||||
width = 4
|
||||
}
|
||||
// length、err 分别是读取出的载荷长度与底层字节读取错误。
|
||||
length, err := d.readLength(width)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decode(length)
|
||||
}
|
||||
|
||||
// readLength 读取指定宽度的无符号大端长度。
|
||||
func (d *msgpackDecoder) readLength(width int) (int, error) {
|
||||
// data、err 分别是长度前缀的原始字节与读取错误。
|
||||
data, err := d.readBytes(width)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch width {
|
||||
case 1:
|
||||
return int(data[0]), nil
|
||||
case 2:
|
||||
return int(binary.BigEndian.Uint16(data)), nil
|
||||
default:
|
||||
return int(binary.BigEndian.Uint32(data)), nil
|
||||
}
|
||||
}
|
||||
|
||||
// readString 封装readString业务协调。
|
||||
func (d *msgpackDecoder) readString(n int) (string, error) {
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
|
||||
@@ -3,10 +3,7 @@ package qrlogin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
rand "crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -14,7 +11,6 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -23,7 +19,6 @@ import (
|
||||
qrcode "github.com/skip2/go-qrcode"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
@@ -404,71 +399,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
status := qrResult.Content.Data.QRCodeStatus
|
||||
switch status {
|
||||
case "CONFIRMED":
|
||||
if qrResult.Content.Data.IframeRedirect {
|
||||
// 风控验证:记录状态和 URL,提取响应 cookie(临时 cookie),
|
||||
// 验证完成后用这些临时 cookie 访问 goofish.com/im 换真实 cookie。
|
||||
sess.mu.Lock()
|
||||
if sess.Status == "success" {
|
||||
sess.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if sess.Status != "verification_required" {
|
||||
sess.Status = "verification_required"
|
||||
sess.verificationURL = qrResult.Content.Data.IframeRedirectURL
|
||||
// 已有权威快照交给可导出的 Go Cookie Jar;它会继续吸收
|
||||
// 人脸跳转链每个重定向响应的 Set-Cookie。
|
||||
// 人脸验证会额外占用用户手机端操作时间。这里重置窗口,避免普通
|
||||
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
|
||||
sess.createdTime = time.Now()
|
||||
sess.expireTime = 5 * time.Minute
|
||||
// verURL 用于本次流程后续判断的verURL
|
||||
verURL := sess.verificationURL
|
||||
// expireTime 用于本次流程后续判断的expire时间
|
||||
expireTime := sess.expireTime
|
||||
// cookieCount 用于本次流程后续判断的登录凭证数量
|
||||
cookieCount := len(sess.cookies)
|
||||
sess.mu.Unlock()
|
||||
m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
|
||||
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
|
||||
go func() {
|
||||
// verifyCtx、cancel 用于本次流程后续判断的verifyCtx、cancel
|
||||
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
|
||||
defer cancel()
|
||||
m.runGoVerification(verifyCtx, sessionID, verURL)
|
||||
}()
|
||||
} else {
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
return
|
||||
}
|
||||
// 二维码组件确认成功后,真实网页还会进入 /im 并跟随登录
|
||||
// 重定向。部分账号的长登录 Cookie 只在这一步下发,不能只
|
||||
// 保存 query.do 的响应头。
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.completeConfirmedLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码确认后的官网登录跳转未完成,保留当前登录凭证", "session_id", sessionID, "err", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.enableConfirmedLongLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码登录已成功,但官网保持登录开启失败", "session_id", sessionID, "err", err)
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.Status = "success"
|
||||
finalizeSessionCredentialsLocked(sess)
|
||||
// unb 用于本次流程后续判断的unb
|
||||
unb := sess.unb
|
||||
// cookieCount 用于本次流程后续判断的登录凭证数量
|
||||
cookieCount := len(sess.cookies)
|
||||
// hasHavanaLongLogin 用于本次流程后续判断的hasHavanaLong登录
|
||||
hasHavanaLongLogin := sess.cookies["havana_lgc_exp"] != ""
|
||||
// hasCookie3Backup 用于本次流程后续判断的hasCookie3Backup
|
||||
hasCookie3Backup := sess.cookies["cookie3_bak_exp"] != ""
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
snapshotComplete := sess.cookieSnapshot != nil
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb),
|
||||
"cookie_count", cookieCount, "cookie_snapshot_complete", snapshotComplete,
|
||||
"has_havana_lgc_exp", hasHavanaLongLogin, "has_cookie3_bak_exp", hasCookie3Backup)
|
||||
m.handleConfirmedQRStatus(ctx, sess, sessionID, qrResult.Content.Data.IframeRedirect, qrResult.Content.Data.IframeRedirectURL)
|
||||
return
|
||||
case "NEW":
|
||||
// 未扫码,继续
|
||||
@@ -643,479 +574,3 @@ func waitQRRetry(ctx context.Context, delay time.Duration) bool {
|
||||
// CompleteVerification 用户完成风控验证后调用。整个凭证换取过程只使用
|
||||
// Go Cookie Jar;不得导航浏览器页面或通过 DOM 判断登录状态。
|
||||
// CompleteVerification 封装CompleteVerification业务协调。
|
||||
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
|
||||
m.mu.Lock()
|
||||
// sess、ok 用于本次流程后续判断的sess、ok
|
||||
sess, ok := m.sessions[sessionID]
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return "", "", fmt.Errorf("会话不存在")
|
||||
}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := sess.snapshot()
|
||||
if len(state.cookies) == 0 {
|
||||
return "", "", fmt.Errorf("无扫码临时 cookie")
|
||||
}
|
||||
if state.status == "success" && state.unb != "" {
|
||||
return snapshotCookieHeader(state, qrVerifyTargetURL), state.unb, nil
|
||||
}
|
||||
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
|
||||
|
||||
// targetURL 用于本次流程后续判断的targetURL
|
||||
targetURL := qrVerifyTargetURL
|
||||
// seedURL 用于本次流程后续判断的seedURL
|
||||
seedURL := state.verificationURL
|
||||
if strings.TrimSpace(seedURL) == "" {
|
||||
seedURL = targetURL
|
||||
}
|
||||
// jarClient、jar、err 用于本次流程后续判断的jarClient、jar、err
|
||||
jarClient, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, seedURL, targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("创建登录 Cookie Jar: %w", err)
|
||||
}
|
||||
jarClient.Timeout = 30 * time.Second
|
||||
// target、err 用于本次流程后续判断的target、err
|
||||
target, err := url.Parse(targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析登录凭证换取地址: %w", err)
|
||||
}
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
m.setDocumentHeaders(req)
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := jarClient.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("访问 goofish.com/im 换取登录凭证失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return "", "", fmt.Errorf("读取登录凭证换取响应失败: %w", err)
|
||||
}
|
||||
// responseURL 用于本次流程后续判断的响应URL
|
||||
var responseURL *url.URL
|
||||
if resp.Request != nil {
|
||||
responseURL = resp.Request.URL
|
||||
}
|
||||
// finalCookies 用于本次流程后续判断的finalCookies
|
||||
finalCookies := collectJarCookies(jar, target, responseURL)
|
||||
// finalUNB 用于本次流程后续判断的finalUNB
|
||||
finalUNB := finalCookies["unb"]
|
||||
if finalUNB == "" {
|
||||
return "", "", fmt.Errorf("纯 Go 登录凭证换取未获取到 unb,验证可能尚未完成或临时 Cookie 已失效")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.cookies = finalCookies
|
||||
if // finalSnapshot、complete 用于本次流程后续判断的finalSnapshot、complete
|
||||
finalSnapshot, complete := jar.Snapshot(); complete {
|
||||
sess.cookieSnapshot = finalSnapshot
|
||||
} else {
|
||||
sess.cookieSnapshot = nil
|
||||
}
|
||||
sess.unb = finalUNB
|
||||
sess.Status = "success"
|
||||
sess.verificationScreenshot = ""
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("纯 Go 提取登录凭证成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
|
||||
return snapshotCookieHeader(sess.snapshot(), qrVerifyTargetURL), finalUNB, nil
|
||||
}
|
||||
|
||||
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
|
||||
func parseCookieStr(s string) map[string]string {
|
||||
// m 用于本次流程后续判断的m
|
||||
m := make(map[string]string)
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(s, "; ") {
|
||||
if // eq 用于本次流程后续判断的eq
|
||||
eq := strings.Index(part, "="); eq >= 0 {
|
||||
m[part[:eq]] = part[eq+1:]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// getMH5TK 获取 m_h5_tk。
|
||||
func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiH5TK, nil)
|
||||
m.setHeaders(req)
|
||||
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := m.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
absorbSessionResponse(sess, apiH5TK, resp)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
// mH5TK 用于本次流程后续判断的mH5TK
|
||||
mH5TK := protocolCookieValue(sessionCookieHeader(sess, apiH5TK), "_m_h5_tk")
|
||||
// token 用于本次流程后续判断的令牌
|
||||
token := ""
|
||||
if // parts 用于本次流程后续判断的parts
|
||||
parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
|
||||
token = parts[0]
|
||||
}
|
||||
|
||||
// t 用于本次流程后续判断的t
|
||||
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
// dataStr 用于本次流程后续判断的数据Str
|
||||
dataStr := `{"bizScene":"home"}`
|
||||
// signInput 用于本次流程后续判断的signInput
|
||||
signInput := token + "&" + t + "&" + appKey + "&" + dataStr
|
||||
// sign 用于本次流程后续判断的sign
|
||||
sign := md5hex(signInput)
|
||||
|
||||
// params 用于本次流程后续判断的params
|
||||
params := url.Values{}
|
||||
params.Set("jsv", "2.7.2")
|
||||
params.Set("appKey", appKey)
|
||||
params.Set("t", t)
|
||||
params.Set("sign", sign)
|
||||
params.Set("v", "1.0")
|
||||
params.Set("type", "originaljson")
|
||||
params.Set("dataType", "json")
|
||||
params.Set("timeout", "20000")
|
||||
params.Set("api", "mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get")
|
||||
params.Set("data", dataStr)
|
||||
|
||||
// req2 用于本次流程后续判断的req2
|
||||
req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil)
|
||||
m.setHeaders(req2)
|
||||
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := sessionCookieHeader(sess, req2.URL.String())
|
||||
if cookieStr != "" {
|
||||
req2.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
// resp2、err 用于本次流程后续判断的resp2、err
|
||||
resp2, err := m.httpc.Do(req2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp2.Body.Close()
|
||||
absorbSessionResponse(sess, req2.URL.String(), resp2)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp2.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getLoginParams 获取登录表单参数。
|
||||
func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string]string, error) {
|
||||
// params 用于本次流程后续判断的params
|
||||
params := url.Values{}
|
||||
params.Set("lang", "zh_cn")
|
||||
params.Set("appName", "xianyu")
|
||||
params.Set("appEntrance", "web")
|
||||
params.Set("styleType", "vertical")
|
||||
params.Set("bizParams", "")
|
||||
params.Set("notLoadSsoView", "false")
|
||||
params.Set("notKeepLogin", "false")
|
||||
params.Set("isMobile", "false")
|
||||
params.Set("qrCodeFirst", "false")
|
||||
params.Set("stie", "77")
|
||||
params.Set("rnd", strconv.FormatFloat(randFloat(), 'f', -1, 64))
|
||||
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiMiniLogin+"?"+params.Encode(), nil)
|
||||
m.setHeaders(req)
|
||||
|
||||
// 带上已有 cookie。
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := m.httpc.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
absorbSessionResponse(sess, req.URL.String(), resp)
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := readQRBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 调试:打印响应状态和 body 前 200 字符
|
||||
|
||||
// 从 HTML 里提取 window.viewData = {...};
|
||||
re := regexp.MustCompile(`window\.viewData\s*=\s*(\{.*?\});`)
|
||||
// match 用于本次流程后续判断的match
|
||||
match := re.FindSubmatch(body)
|
||||
if match == nil {
|
||||
return nil, fmt.Errorf("获取登录参数失败:未找到 viewData")
|
||||
}
|
||||
|
||||
// viewData 用于本次流程后续判断的view数据
|
||||
var viewData struct {
|
||||
LoginFormData map[string]any `json:"loginFormData"`
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal(match[1], &viewData); err != nil {
|
||||
return nil, fmt.Errorf("解析 viewData 失败: %w", err)
|
||||
}
|
||||
if viewData.LoginFormData == nil {
|
||||
return nil, fmt.Errorf("loginFormData 为空")
|
||||
}
|
||||
// 把所有值转为字符串(有些是 bool/number)。
|
||||
strParams := make(map[string]string, len(viewData.LoginFormData))
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range viewData.LoginFormData {
|
||||
strParams[k] = fmt.Sprintf("%v", v)
|
||||
}
|
||||
strParams["umidTag"] = "SERVER"
|
||||
sess.mu.Lock()
|
||||
sess.params = strParams
|
||||
sess.mu.Unlock()
|
||||
return strParams, nil
|
||||
}
|
||||
|
||||
// pollQRCodeStatus 轮询二维码状态。
|
||||
func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Response, error) {
|
||||
// form 用于本次流程后续判断的表单
|
||||
form := url.Values{}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := sess.snapshot()
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range state.params {
|
||||
form.Set(k, v)
|
||||
}
|
||||
// fingerprint 用于本次流程后续判断的fingerprint
|
||||
fingerprint := xianyu.CurrentBrowserFingerprint()
|
||||
// 对齐 havana-nlogin 二维码组件 query.do 的浏览器环境字段。
|
||||
// ua 是 AWSC/UAB 的可选结果;纯 Go 客户端在该值尚未生成时与官网
|
||||
// 脚本一样发送空值,不借助 Chromium 执行业务页面脚本。
|
||||
form.Set("ua", "")
|
||||
form.Set("navlanguage", "zh-CN")
|
||||
form.Set("navUserAgent", fingerprint.UserAgent)
|
||||
form.Set("navPlatform", navigatorPlatform(fingerprint.Platform))
|
||||
form.Set("isIframe", "true")
|
||||
form.Set("documentReferer", qrVerifyTargetURL)
|
||||
form.Set("defaultView", "qrcode")
|
||||
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
m.setHeaders(req)
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
return m.httpc.Do(req)
|
||||
}
|
||||
|
||||
// navigatorPlatform 封装navigatorPlatform业务协调。
|
||||
func navigatorPlatform(secCHPlatform string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(secCHPlatform)) {
|
||||
case "windows":
|
||||
return "Win32"
|
||||
case "macos":
|
||||
return "MacIntel"
|
||||
case "linux":
|
||||
return "Linux x86_64"
|
||||
case "android":
|
||||
return "Linux armv8l"
|
||||
case "ios":
|
||||
return "iPhone"
|
||||
default:
|
||||
return strings.TrimSpace(secCHPlatform)
|
||||
}
|
||||
}
|
||||
|
||||
// setHeaders 封装setHeaders业务协调。
|
||||
func (m *Manager) setHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range qrHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// setDocumentHeaders 复刻浏览器从闲鱼首页进入 /im 的文档请求头。这里只
|
||||
// 发送 HTTP 请求并接收 Set-Cookie,不加载或校验任何页面 DOM。
|
||||
// setDocumentHeaders 封装setDocumentHeaders业务协调。
|
||||
func (m *Manager) setDocumentHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Referer", "https://www.goofish.com/")
|
||||
req.Header.Set("Sec-Fetch-Dest", "document")
|
||||
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
req.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
}
|
||||
|
||||
// sessionCookieHeader 封装会话登录凭证Header业务协调。
|
||||
func sessionCookieHeader(sess *Session, requestURL string) string {
|
||||
if sess == nil {
|
||||
return ""
|
||||
}
|
||||
return snapshotCookieHeader(sess.snapshot(), requestURL)
|
||||
}
|
||||
|
||||
// snapshotCookieHeader 封装snapshot登录凭证Header业务协调。
|
||||
func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
|
||||
if state.cookieSnapshot != nil {
|
||||
if // value、authoritative 用于本次流程后续判断的value、authoritative
|
||||
value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
state.cookieSnapshot, requestURL, qrTopSite, time.Now(),
|
||||
); authoritative {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return cookieMarshal(state.cookies)
|
||||
}
|
||||
|
||||
// absorbSessionResponse 封装absorb会话响应业务协调。
|
||||
func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response) {
|
||||
if sess == nil || resp == nil {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
if sess.cookieSnapshot != nil {
|
||||
sess.cookieSnapshot = cookierefresh.ApplySetCookies(
|
||||
sess.cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), qrTopSite,
|
||||
)
|
||||
if sess.cookieSnapshot == nil {
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range resp.Cookies() {
|
||||
if cookie == nil || cookie.Name == "" {
|
||||
continue
|
||||
}
|
||||
if cookie.MaxAge < 0 || (!cookie.Expires.IsZero() && !cookie.Expires.After(time.Now())) {
|
||||
delete(sess.cookies, cookie.Name)
|
||||
if cookie.Name == "unb" {
|
||||
sess.unb = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
sess.cookies[cookie.Name] = cookie.Value
|
||||
if cookie.Name == "unb" && cookie.Value != "" {
|
||||
sess.unb = cookie.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeSessionCredentialsLocked 封装finalize会话CredentialsLocked业务协调。
|
||||
func finalizeSessionCredentialsLocked(sess *Session) {
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
if sess.cookieSnapshot != nil {
|
||||
// value 用于本次流程后续判断的值
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
sess.cookieSnapshot, qrVerifyTargetURL, qrTopSite, time.Now(),
|
||||
)
|
||||
sess.cookies = parseCookieStr(value)
|
||||
}
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := sess.cookies["unb"]; unb != "" {
|
||||
sess.unb = unb
|
||||
}
|
||||
}
|
||||
|
||||
// cloneCookieSnapshot 封装clone登录凭证Snapshot业务协调。
|
||||
func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
// out 用于本次流程后续判断的out
|
||||
out := cookierefresh.NormalizeSnapshot(in)
|
||||
if out == nil {
|
||||
return []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// protocolCookieValue 封装protocol登录凭证值业务协调。
|
||||
func protocolCookieValue(cookieHeader, name string) string {
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(cookieHeader, ";") {
|
||||
// key、value、ok 用于本次流程后续判断的key、value、ok
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
if ok && key == name {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---- 工具函数 ----
|
||||
|
||||
// md5hex 封装md5hex业务协调。
|
||||
func md5hex(s string) string {
|
||||
// #nosec G401 -- 闲鱼登录协议明确要求 MD5,不能替换为其他摘要算法。
|
||||
h := md5.Sum([]byte(s))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// cookieMarshal 封装登录凭证Marshal业务协调。
|
||||
func cookieMarshal(cookies map[string]string) string {
|
||||
// parts 用于本次流程后续判断的parts
|
||||
parts := make([]string, 0, len(cookies))
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range cookies {
|
||||
parts = append(parts, k+"="+v)
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// randomUUID 封装randomUUID业务协调。
|
||||
func randomUUID() (string, error) {
|
||||
// b 用于本次流程后续判断的b
|
||||
b := make([]byte, 16)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.ReadFull(randReader, b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
// randReader 用于本次流程后续判断的randReader
|
||||
var randReader io.Reader = rand.Reader
|
||||
|
||||
// randFloat 用于本次流程后续判断的randFloat
|
||||
var randFloat = func() float64 { return float64(time.Now().UnixNano()%1e9) / 1e9 }
|
||||
|
||||
// readQRBody 封装readQR请求体业务协调。
|
||||
func readQRBody(r io.Reader) ([]byte, error) {
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := io.ReadAll(io.LimitReader(r, maxQRResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(body) > maxQRResponseBytes {
|
||||
return nil, fmt.Errorf("扫码登录响应体超过 %d MiB", maxQRResponseBytes>>20)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// truncate 封装truncate业务协调。
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package qrlogin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
)
|
||||
|
||||
// handleConfirmedQRStatus 完成确认扫码后的风控分流或官网登录收口;两条路径都终止当前轮询。
|
||||
func (m *Manager) handleConfirmedQRStatus(ctx context.Context, sess *Session, sessionID string, iframeRedirect bool, verificationURL string) {
|
||||
if iframeRedirect {
|
||||
// 风控验证:记录状态和 URL,提取响应 cookie(临时 cookie),
|
||||
// 验证完成后用这些临时 cookie 访问 goofish.com/im 换真实 cookie。
|
||||
sess.mu.Lock()
|
||||
if sess.Status == "success" {
|
||||
sess.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if sess.Status != "verification_required" {
|
||||
sess.Status = "verification_required"
|
||||
sess.verificationURL = verificationURL
|
||||
// 已有权威快照交给可导出的 Go Cookie Jar;它会继续吸收
|
||||
// 人脸跳转链每个重定向响应的 Set-Cookie。
|
||||
// 人脸验证会额外占用用户手机端操作时间。这里重置窗口,避免普通
|
||||
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
|
||||
sess.createdTime = time.Now()
|
||||
sess.expireTime = 5 * time.Minute
|
||||
// verURL 用于本次流程后续判断的verURL
|
||||
verURL := sess.verificationURL
|
||||
// expireTime 用于本次流程后续判断的expire时间
|
||||
expireTime := sess.expireTime
|
||||
// cookieCount 用于本次流程后续判断的登录凭证数量
|
||||
cookieCount := len(sess.cookies)
|
||||
sess.mu.Unlock()
|
||||
m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
|
||||
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
|
||||
go func() {
|
||||
// verifyCtx、cancel 用于本次流程后续判断的verifyCtx、cancel
|
||||
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
|
||||
defer cancel()
|
||||
m.runGoVerification(verifyCtx, sessionID, verURL)
|
||||
}()
|
||||
} else {
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
return
|
||||
}
|
||||
// 二维码组件确认成功后,真实网页还会进入 /im 并跟随登录
|
||||
// 重定向。部分账号的长登录 Cookie 只在这一步下发,不能只
|
||||
// 保存 query.do 的响应头。
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.completeConfirmedLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码确认后的官网登录跳转未完成,保留当前登录凭证", "session_id", sessionID, "err", err)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.enableConfirmedLongLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码登录已成功,但官网保持登录开启失败", "session_id", sessionID, "err", err)
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.Status = "success"
|
||||
finalizeSessionCredentialsLocked(sess)
|
||||
// unb 用于本次流程后续判断的unb
|
||||
unb := sess.unb
|
||||
// cookieCount 用于本次流程后续判断的登录凭证数量
|
||||
cookieCount := len(sess.cookies)
|
||||
// hasHavanaLongLogin 用于本次流程后续判断的hasHavanaLong登录
|
||||
hasHavanaLongLogin := sess.cookies["havana_lgc_exp"] != ""
|
||||
// hasCookie3Backup 用于本次流程后续判断的hasCookie3Backup
|
||||
hasCookie3Backup := sess.cookies["cookie3_bak_exp"] != ""
|
||||
// snapshotComplete 用于本次流程后续判断的snapshotComplete
|
||||
snapshotComplete := sess.cookieSnapshot != nil
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb),
|
||||
"cookie_count", cookieCount, "cookie_snapshot_complete", snapshotComplete,
|
||||
"has_havana_lgc_exp", hasHavanaLongLogin, "has_cookie3_bak_exp", hasCookie3Backup)
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
package qrlogin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
rand "crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// CompleteVerification 完成已确认扫码会话的人工验证并返回最终凭证与平台账号标识。
|
||||
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
|
||||
m.mu.Lock()
|
||||
// sess、ok 用于本次流程后续判断的sess、ok
|
||||
sess, ok := m.sessions[sessionID]
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return "", "", fmt.Errorf("会话不存在")
|
||||
}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := sess.snapshot()
|
||||
if len(state.cookies) == 0 {
|
||||
return "", "", fmt.Errorf("无扫码临时 cookie")
|
||||
}
|
||||
if state.status == "success" && state.unb != "" {
|
||||
return snapshotCookieHeader(state, qrVerifyTargetURL), state.unb, nil
|
||||
}
|
||||
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
|
||||
|
||||
// targetURL 用于本次流程后续判断的targetURL
|
||||
targetURL := qrVerifyTargetURL
|
||||
// seedURL 用于本次流程后续判断的seedURL
|
||||
seedURL := state.verificationURL
|
||||
if strings.TrimSpace(seedURL) == "" {
|
||||
seedURL = targetURL
|
||||
}
|
||||
// jarClient、jar、err 用于本次流程后续判断的jarClient、jar、err
|
||||
jarClient, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, seedURL, targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("创建登录 Cookie Jar: %w", err)
|
||||
}
|
||||
jarClient.Timeout = 30 * time.Second
|
||||
// target、err 用于本次流程后续判断的target、err
|
||||
target, err := url.Parse(targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析登录凭证换取地址: %w", err)
|
||||
}
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
m.setDocumentHeaders(req)
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := jarClient.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("访问 goofish.com/im 换取登录凭证失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return "", "", fmt.Errorf("读取登录凭证换取响应失败: %w", err)
|
||||
}
|
||||
// responseURL 用于本次流程后续判断的响应URL
|
||||
var responseURL *url.URL
|
||||
if resp.Request != nil {
|
||||
responseURL = resp.Request.URL
|
||||
}
|
||||
// finalCookies 用于本次流程后续判断的finalCookies
|
||||
finalCookies := collectJarCookies(jar, target, responseURL)
|
||||
// finalUNB 用于本次流程后续判断的finalUNB
|
||||
finalUNB := finalCookies["unb"]
|
||||
if finalUNB == "" {
|
||||
return "", "", fmt.Errorf("纯 Go 登录凭证换取未获取到 unb,验证可能尚未完成或临时 Cookie 已失效")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.cookies = finalCookies
|
||||
if // finalSnapshot、complete 用于本次流程后续判断的finalSnapshot、complete
|
||||
finalSnapshot, complete := jar.Snapshot(); complete {
|
||||
sess.cookieSnapshot = finalSnapshot
|
||||
} else {
|
||||
sess.cookieSnapshot = nil
|
||||
}
|
||||
sess.unb = finalUNB
|
||||
sess.Status = "success"
|
||||
sess.verificationScreenshot = ""
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("纯 Go 提取登录凭证成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
|
||||
return snapshotCookieHeader(sess.snapshot(), qrVerifyTargetURL), finalUNB, nil
|
||||
}
|
||||
|
||||
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
|
||||
func parseCookieStr(s string) map[string]string {
|
||||
// m 用于本次流程后续判断的m
|
||||
m := make(map[string]string)
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(s, "; ") {
|
||||
if // eq 用于本次流程后续判断的eq
|
||||
eq := strings.Index(part, "="); eq >= 0 {
|
||||
m[part[:eq]] = part[eq+1:]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// getMH5TK 获取 m_h5_tk。
|
||||
func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiH5TK, nil)
|
||||
m.setHeaders(req)
|
||||
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := m.httpc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
absorbSessionResponse(sess, apiH5TK, resp)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
// mH5TK 用于本次流程后续判断的mH5TK
|
||||
mH5TK := protocolCookieValue(sessionCookieHeader(sess, apiH5TK), "_m_h5_tk")
|
||||
// token 用于本次流程后续判断的令牌
|
||||
token := ""
|
||||
if // parts 用于本次流程后续判断的parts
|
||||
parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
|
||||
token = parts[0]
|
||||
}
|
||||
|
||||
// t 用于本次流程后续判断的t
|
||||
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
// dataStr 用于本次流程后续判断的数据Str
|
||||
dataStr := `{"bizScene":"home"}`
|
||||
// signInput 用于本次流程后续判断的signInput
|
||||
signInput := token + "&" + t + "&" + appKey + "&" + dataStr
|
||||
// sign 用于本次流程后续判断的sign
|
||||
sign := md5hex(signInput)
|
||||
|
||||
// params 用于本次流程后续判断的params
|
||||
params := url.Values{}
|
||||
params.Set("jsv", "2.7.2")
|
||||
params.Set("appKey", appKey)
|
||||
params.Set("t", t)
|
||||
params.Set("sign", sign)
|
||||
params.Set("v", "1.0")
|
||||
params.Set("type", "originaljson")
|
||||
params.Set("dataType", "json")
|
||||
params.Set("timeout", "20000")
|
||||
params.Set("api", "mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get")
|
||||
params.Set("data", dataStr)
|
||||
|
||||
// req2 用于本次流程后续判断的req2
|
||||
req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil)
|
||||
m.setHeaders(req2)
|
||||
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := sessionCookieHeader(sess, req2.URL.String())
|
||||
if cookieStr != "" {
|
||||
req2.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
// resp2、err 用于本次流程后续判断的resp2、err
|
||||
resp2, err := m.httpc.Do(req2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp2.Body.Close()
|
||||
absorbSessionResponse(sess, req2.URL.String(), resp2)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.Copy(io.Discard, resp2.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getLoginParams 获取登录表单参数。
|
||||
func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string]string, error) {
|
||||
// params 用于本次流程后续判断的params
|
||||
params := url.Values{}
|
||||
params.Set("lang", "zh_cn")
|
||||
params.Set("appName", "xianyu")
|
||||
params.Set("appEntrance", "web")
|
||||
params.Set("styleType", "vertical")
|
||||
params.Set("bizParams", "")
|
||||
params.Set("notLoadSsoView", "false")
|
||||
params.Set("notKeepLogin", "false")
|
||||
params.Set("isMobile", "false")
|
||||
params.Set("qrCodeFirst", "false")
|
||||
params.Set("stie", "77")
|
||||
params.Set("rnd", strconv.FormatFloat(randFloat(), 'f', -1, 64))
|
||||
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiMiniLogin+"?"+params.Encode(), nil)
|
||||
m.setHeaders(req)
|
||||
|
||||
// 带上已有 cookie。
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := m.httpc.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
absorbSessionResponse(sess, req.URL.String(), resp)
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := readQRBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 调试:打印响应状态和 body 前 200 字符
|
||||
|
||||
// 从 HTML 里提取 window.viewData = {...};
|
||||
re := regexp.MustCompile(`window\.viewData\s*=\s*(\{.*?\});`)
|
||||
// match 用于本次流程后续判断的match
|
||||
match := re.FindSubmatch(body)
|
||||
if match == nil {
|
||||
return nil, fmt.Errorf("获取登录参数失败:未找到 viewData")
|
||||
}
|
||||
|
||||
// viewData 用于本次流程后续判断的view数据
|
||||
var viewData struct {
|
||||
LoginFormData map[string]any `json:"loginFormData"`
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal(match[1], &viewData); err != nil {
|
||||
return nil, fmt.Errorf("解析 viewData 失败: %w", err)
|
||||
}
|
||||
if viewData.LoginFormData == nil {
|
||||
return nil, fmt.Errorf("loginFormData 为空")
|
||||
}
|
||||
// 把所有值转为字符串(有些是 bool/number)。
|
||||
strParams := make(map[string]string, len(viewData.LoginFormData))
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range viewData.LoginFormData {
|
||||
strParams[k] = fmt.Sprintf("%v", v)
|
||||
}
|
||||
strParams["umidTag"] = "SERVER"
|
||||
sess.mu.Lock()
|
||||
sess.params = strParams
|
||||
sess.mu.Unlock()
|
||||
return strParams, nil
|
||||
}
|
||||
|
||||
// pollQRCodeStatus 轮询二维码状态。
|
||||
func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Response, error) {
|
||||
// form 用于本次流程后续判断的表单
|
||||
form := url.Values{}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := sess.snapshot()
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range state.params {
|
||||
form.Set(k, v)
|
||||
}
|
||||
// fingerprint 用于本次流程后续判断的fingerprint
|
||||
fingerprint := xianyu.CurrentBrowserFingerprint()
|
||||
// 对齐 havana-nlogin 二维码组件 query.do 的浏览器环境字段。
|
||||
// ua 是 AWSC/UAB 的可选结果;纯 Go 客户端在该值尚未生成时与官网
|
||||
// 脚本一样发送空值,不借助 Chromium 执行业务页面脚本。
|
||||
form.Set("ua", "")
|
||||
form.Set("navlanguage", "zh-CN")
|
||||
form.Set("navUserAgent", fingerprint.UserAgent)
|
||||
form.Set("navPlatform", navigatorPlatform(fingerprint.Platform))
|
||||
form.Set("isIframe", "true")
|
||||
form.Set("documentReferer", qrVerifyTargetURL)
|
||||
form.Set("defaultView", "qrcode")
|
||||
|
||||
// req 用于本次流程后续判断的req
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
m.setHeaders(req)
|
||||
// cookieStr 用于本次流程后续判断的登录凭证Str
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
return m.httpc.Do(req)
|
||||
}
|
||||
|
||||
// navigatorPlatform 封装navigatorPlatform业务协调。
|
||||
func navigatorPlatform(secCHPlatform string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(secCHPlatform)) {
|
||||
case "windows":
|
||||
return "Win32"
|
||||
case "macos":
|
||||
return "MacIntel"
|
||||
case "linux":
|
||||
return "Linux x86_64"
|
||||
case "android":
|
||||
return "Linux armv8l"
|
||||
case "ios":
|
||||
return "iPhone"
|
||||
default:
|
||||
return strings.TrimSpace(secCHPlatform)
|
||||
}
|
||||
}
|
||||
|
||||
// setHeaders 封装setHeaders业务协调。
|
||||
func (m *Manager) setHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range qrHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
// setDocumentHeaders 复刻浏览器从闲鱼首页进入 /im 的文档请求头。这里只
|
||||
// 发送 HTTP 请求并接收 Set-Cookie,不加载或校验任何页面 DOM。
|
||||
// setDocumentHeaders 封装setDocumentHeaders业务协调。
|
||||
func (m *Manager) setDocumentHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Referer", "https://www.goofish.com/")
|
||||
req.Header.Set("Sec-Fetch-Dest", "document")
|
||||
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
req.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
}
|
||||
|
||||
// sessionCookieHeader 封装会话登录凭证Header业务协调。
|
||||
func sessionCookieHeader(sess *Session, requestURL string) string {
|
||||
if sess == nil {
|
||||
return ""
|
||||
}
|
||||
return snapshotCookieHeader(sess.snapshot(), requestURL)
|
||||
}
|
||||
|
||||
// snapshotCookieHeader 封装snapshot登录凭证Header业务协调。
|
||||
func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
|
||||
if state.cookieSnapshot != nil {
|
||||
if // value、authoritative 用于本次流程后续判断的value、authoritative
|
||||
value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
state.cookieSnapshot, requestURL, qrTopSite, time.Now(),
|
||||
); authoritative {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return cookieMarshal(state.cookies)
|
||||
}
|
||||
|
||||
// absorbSessionResponse 封装absorb会话响应业务协调。
|
||||
func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response) {
|
||||
if sess == nil || resp == nil {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
if sess.cookieSnapshot != nil {
|
||||
sess.cookieSnapshot = cookierefresh.ApplySetCookies(
|
||||
sess.cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), qrTopSite,
|
||||
)
|
||||
if sess.cookieSnapshot == nil {
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range resp.Cookies() {
|
||||
if cookie == nil || cookie.Name == "" {
|
||||
continue
|
||||
}
|
||||
if cookie.MaxAge < 0 || (!cookie.Expires.IsZero() && !cookie.Expires.After(time.Now())) {
|
||||
delete(sess.cookies, cookie.Name)
|
||||
if cookie.Name == "unb" {
|
||||
sess.unb = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
sess.cookies[cookie.Name] = cookie.Value
|
||||
if cookie.Name == "unb" && cookie.Value != "" {
|
||||
sess.unb = cookie.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeSessionCredentialsLocked 封装finalize会话CredentialsLocked业务协调。
|
||||
func finalizeSessionCredentialsLocked(sess *Session) {
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
if sess.cookieSnapshot != nil {
|
||||
// value 用于本次流程后续判断的值
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
sess.cookieSnapshot, qrVerifyTargetURL, qrTopSite, time.Now(),
|
||||
)
|
||||
sess.cookies = parseCookieStr(value)
|
||||
}
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := sess.cookies["unb"]; unb != "" {
|
||||
sess.unb = unb
|
||||
}
|
||||
}
|
||||
|
||||
// cloneCookieSnapshot 封装clone登录凭证Snapshot业务协调。
|
||||
func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
// out 用于本次流程后续判断的out
|
||||
out := cookierefresh.NormalizeSnapshot(in)
|
||||
if out == nil {
|
||||
return []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// protocolCookieValue 封装protocol登录凭证值业务协调。
|
||||
func protocolCookieValue(cookieHeader, name string) string {
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(cookieHeader, ";") {
|
||||
// key、value、ok 用于本次流程后续判断的key、value、ok
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
if ok && key == name {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---- 工具函数 ----
|
||||
|
||||
// md5hex 封装md5hex业务协调。
|
||||
func md5hex(s string) string {
|
||||
// #nosec G401 -- 闲鱼登录协议明确要求 MD5,不能替换为其他摘要算法。
|
||||
h := md5.Sum([]byte(s))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// cookieMarshal 封装登录凭证Marshal业务协调。
|
||||
func cookieMarshal(cookies map[string]string) string {
|
||||
// parts 用于本次流程后续判断的parts
|
||||
parts := make([]string, 0, len(cookies))
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range cookies {
|
||||
parts = append(parts, k+"="+v)
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// randomUUID 封装randomUUID业务协调。
|
||||
func randomUUID() (string, error) {
|
||||
// b 用于本次流程后续判断的b
|
||||
b := make([]byte, 16)
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := io.ReadFull(randReader, b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
// randReader 用于本次流程后续判断的randReader
|
||||
var randReader io.Reader = rand.Reader
|
||||
|
||||
// randFloat 用于本次流程后续判断的randFloat
|
||||
var randFloat = func() float64 { return float64(time.Now().UnixNano()%1e9) / 1e9 }
|
||||
|
||||
// readQRBody 封装readQR请求体业务协调。
|
||||
func readQRBody(r io.Reader) ([]byte, error) {
|
||||
// body、err 用于本次流程后续判断的body、err
|
||||
body, err := io.ReadAll(io.LimitReader(r, maxQRResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(body) > maxQRResponseBytes {
|
||||
return nil, fmt.Errorf("扫码登录响应体超过 %d MiB", maxQRResponseBytes>>20)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// truncate 封装truncate业务协调。
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package renew
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// longLoginCookieState 用于本次流程后续判断的long登录登录凭证状态
|
||||
type longLoginCookieState struct {
|
||||
flat string
|
||||
snapshot []cookierefresh.BrowserCookie
|
||||
authoritative bool
|
||||
}
|
||||
|
||||
// newLongLoginCookieState 封装newLong登录登录凭证状态业务协调。
|
||||
func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.BrowserCookie) *longLoginCookieState {
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := &longLoginCookieState{flat: cookiesStr, authoritative: len(snapshots) > 0}
|
||||
if state.authoritative {
|
||||
state.snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if state.snapshot == nil {
|
||||
state.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
state.refreshCanonical()
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// requestCookies 封装请求Cookies业务协调。
|
||||
func (state *longLoginCookieState) requestCookies(requestURL string) string {
|
||||
if state == nil || !state.authoritative {
|
||||
if state == nil {
|
||||
return ""
|
||||
}
|
||||
return state.flat
|
||||
}
|
||||
// value 用于本次流程后续判断的值
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, requestURL, goofishTopSite, time.Now())
|
||||
return value
|
||||
}
|
||||
|
||||
// apply 封装apply业务协调。
|
||||
func (state *longLoginCookieState) apply(requestURL string, setCookies []string) {
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
if state.authoritative {
|
||||
state.snapshot = cookierefresh.ApplySetCookies(state.snapshot, requestURL, setCookies, time.Now(), goofishTopSite)
|
||||
if state.snapshot == nil {
|
||||
state.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
state.refreshCanonical()
|
||||
return
|
||||
}
|
||||
state.flat = MergeSetCookies(state.flat, setCookies)
|
||||
}
|
||||
|
||||
// refreshCanonical 封装refreshCanonical业务协调。
|
||||
func (state *longLoginCookieState) refreshCanonical() {
|
||||
state.flat, _ = cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, goofishIMDocumentURL, goofishTopSite, time.Now())
|
||||
}
|
||||
|
||||
// populate 封装populate业务协调。
|
||||
func (state *longLoginCookieState) populate(result *LongLoginSettings) {
|
||||
if state == nil || result == nil {
|
||||
return
|
||||
}
|
||||
result.NewCookies = state.flat
|
||||
result.CookieSnapshotComplete = state.authoritative
|
||||
if state.authoritative {
|
||||
result.CookieSnapshot = cookierefresh.NormalizeSnapshot(state.snapshot)
|
||||
if result.CookieSnapshot == nil {
|
||||
result.CookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。
|
||||
func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
|
||||
return s.longLoginRequest(ctx, newLongLoginCookieState(cookiesStr, snapshots), nil)
|
||||
}
|
||||
|
||||
// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
|
||||
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := "1"
|
||||
if enabled {
|
||||
status = "0"
|
||||
}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := newLongLoginCookieState(cookiesStr, snapshots)
|
||||
// setResult、err 用于本次流程后续判断的setResult、err
|
||||
setResult, err := s.longLoginRequest(ctx, state, &status)
|
||||
if err != nil {
|
||||
return setResult, err
|
||||
}
|
||||
// 官网 SET 成功后触发 LONG_LOGIN_SWITCH,再通过 QUERY 获取最终状态;SET
|
||||
// 本身只要求 data.success,不要求携带 returnValue。
|
||||
// queried、err 用于本次流程后续判断的queried、err
|
||||
queried, err := s.longLoginRequest(ctx, state, nil)
|
||||
if queried == nil {
|
||||
queried = &LongLoginSettings{
|
||||
Enabled: enabled,
|
||||
}
|
||||
state.populate(queried)
|
||||
}
|
||||
queried.SetCookies = append(append([]string(nil), setResult.SetCookies...), queried.SetCookies...)
|
||||
if err != nil {
|
||||
// QUERY 失败时仍返回 SET 请求及 QUERY 响应头已经刷新的 Cookie;最终
|
||||
// 开关状态尚未确认,只能保留调用方本次请求的目标值。
|
||||
queried.Enabled = enabled
|
||||
return queried, err
|
||||
}
|
||||
return queried, nil
|
||||
}
|
||||
|
||||
// longLoginRequest 封装long登录请求业务协调。
|
||||
func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCookieState, status *string) (*LongLoginSettings, error) {
|
||||
// partial 用于本次流程后续判断的partial
|
||||
partial := &LongLoginSettings{}
|
||||
cookieState.populate(partial)
|
||||
if status != nil {
|
||||
partial.Enabled = *status == "0"
|
||||
}
|
||||
// cookieURL 用于本次流程后续判断的登录凭证URL
|
||||
cookieURL := QueryLoginSettingsURL
|
||||
// target 用于本次流程后续判断的target
|
||||
target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
|
||||
// body 用于本次流程后续判断的请求体
|
||||
var body io.Reader
|
||||
if status != nil {
|
||||
cookieURL = SetLoginSettingsURL
|
||||
target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
|
||||
body = strings.NewReader("status=" + url.QueryEscape(*status))
|
||||
}
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
|
||||
if err != nil {
|
||||
return partial, err
|
||||
}
|
||||
appendOrderedQuery(req.URL, [][2]string{{"fromSite", "77"}, {"appName", "xianyu"}, {"bizEntrance", "web"}})
|
||||
setSilentHasLoginHeaders(req, cookieState.requestCookies(cookieURL), s.documentReferer())
|
||||
if status != nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
// hc 用于本次流程后续判断的hc
|
||||
hc := s.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: longLoginRequestTimout}
|
||||
}
|
||||
// requestCtx、cancel 用于本次流程后续判断的请求Ctx、cancel
|
||||
requestCtx, cancel := context.WithTimeout(req.Context(), longLoginRequestTimout)
|
||||
defer cancel()
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := hc.Do(req.Clone(requestCtx))
|
||||
if err != nil {
|
||||
return partial, fmt.Errorf("保存登录信息请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// 浏览器在响应头到达时就会更新 Cookie Jar;因此必须先捕获 Set-Cookie,
|
||||
// 即使随后读取响应体、校验 HTTP 状态或解析业务 JSON 失败也要返回给调用方。
|
||||
partial.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
|
||||
cookieState.apply(cookieURL, partial.SetCookies)
|
||||
cookieState.populate(partial)
|
||||
// raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := readRenewBody(resp.Body)
|
||||
if err != nil {
|
||||
return partial, fmt.Errorf("保存登录信息响应读取失败: %w", err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return partial, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
|
||||
}
|
||||
if status != nil {
|
||||
if !longLoginSetBusinessOK(raw) {
|
||||
return partial, fmt.Errorf("保存登录信息业务结果未确认成功")
|
||||
}
|
||||
return partial, nil
|
||||
}
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := findReturnValue(raw)
|
||||
if !ok {
|
||||
return partial, fmt.Errorf("保存登录信息响应缺少 returnValue")
|
||||
}
|
||||
partial.CanOpenLongLogin, _ = value["canOpenLongLogin"].(bool)
|
||||
partial.Enabled, _ = value["hasLongTokenLogin"].(bool)
|
||||
return partial, nil
|
||||
}
|
||||
|
||||
// longLoginSetBusinessOK 封装long登录SetBusinessOK业务协调。
|
||||
func longLoginSetBusinessOK(raw []byte) bool {
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return false
|
||||
}
|
||||
if // success 用于本次流程后续判断的success
|
||||
success, _ := payload["success"].(bool); success {
|
||||
return true
|
||||
}
|
||||
if // data 用于本次流程后续判断的数据
|
||||
data, _ := payload["data"].(map[string]any); data != nil {
|
||||
// success 用于本次流程后续判断的success
|
||||
success, _ := data["success"].(bool)
|
||||
return success
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// findReturnValue 封装findReturn值业务协调。
|
||||
func findReturnValue(raw []byte) (map[string]any, bool) {
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, false
|
||||
}
|
||||
return findMapChild(payload, "returnValue", 0)
|
||||
}
|
||||
|
||||
// findMapChild 封装findMapChild业务协调。
|
||||
func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) {
|
||||
if parent == nil || depth > 6 {
|
||||
return nil, false
|
||||
}
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := parent[key].(map[string]any); ok {
|
||||
return value, true
|
||||
}
|
||||
// child 表示当前遍历过程中的child
|
||||
for _, child := range parent {
|
||||
if // nested、ok 用于本次流程后续判断的nested、ok
|
||||
nested, ok := child.(map[string]any); ok {
|
||||
if // value、found 用于本次流程后续判断的value、found
|
||||
value, found := findMapChild(nested, key, depth+1); found {
|
||||
return value, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -58,239 +58,6 @@ type LongLoginSettings struct {
|
||||
CookieSnapshotComplete bool `json:"-"`
|
||||
}
|
||||
|
||||
// longLoginCookieState 用于本次流程后续判断的long登录登录凭证状态
|
||||
type longLoginCookieState struct {
|
||||
flat string
|
||||
snapshot []cookierefresh.BrowserCookie
|
||||
authoritative bool
|
||||
}
|
||||
|
||||
// newLongLoginCookieState 封装newLong登录登录凭证状态业务协调。
|
||||
func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.BrowserCookie) *longLoginCookieState {
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := &longLoginCookieState{flat: cookiesStr, authoritative: len(snapshots) > 0}
|
||||
if state.authoritative {
|
||||
state.snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if state.snapshot == nil {
|
||||
state.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
state.refreshCanonical()
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// requestCookies 封装请求Cookies业务协调。
|
||||
func (state *longLoginCookieState) requestCookies(requestURL string) string {
|
||||
if state == nil || !state.authoritative {
|
||||
if state == nil {
|
||||
return ""
|
||||
}
|
||||
return state.flat
|
||||
}
|
||||
// value 用于本次流程后续判断的值
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, requestURL, goofishTopSite, time.Now())
|
||||
return value
|
||||
}
|
||||
|
||||
// apply 封装apply业务协调。
|
||||
func (state *longLoginCookieState) apply(requestURL string, setCookies []string) {
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
if state.authoritative {
|
||||
state.snapshot = cookierefresh.ApplySetCookies(state.snapshot, requestURL, setCookies, time.Now(), goofishTopSite)
|
||||
if state.snapshot == nil {
|
||||
state.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
state.refreshCanonical()
|
||||
return
|
||||
}
|
||||
state.flat = MergeSetCookies(state.flat, setCookies)
|
||||
}
|
||||
|
||||
// refreshCanonical 封装refreshCanonical业务协调。
|
||||
func (state *longLoginCookieState) refreshCanonical() {
|
||||
state.flat, _ = cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, goofishIMDocumentURL, goofishTopSite, time.Now())
|
||||
}
|
||||
|
||||
// populate 封装populate业务协调。
|
||||
func (state *longLoginCookieState) populate(result *LongLoginSettings) {
|
||||
if state == nil || result == nil {
|
||||
return
|
||||
}
|
||||
result.NewCookies = state.flat
|
||||
result.CookieSnapshotComplete = state.authoritative
|
||||
if state.authoritative {
|
||||
result.CookieSnapshot = cookierefresh.NormalizeSnapshot(state.snapshot)
|
||||
if result.CookieSnapshot == nil {
|
||||
result.CookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。
|
||||
func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
|
||||
return s.longLoginRequest(ctx, newLongLoginCookieState(cookiesStr, snapshots), nil)
|
||||
}
|
||||
|
||||
// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
|
||||
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
|
||||
// status 用于本次流程后续判断的状态
|
||||
status := "1"
|
||||
if enabled {
|
||||
status = "0"
|
||||
}
|
||||
// state 用于本次流程后续判断的状态
|
||||
state := newLongLoginCookieState(cookiesStr, snapshots)
|
||||
// setResult、err 用于本次流程后续判断的setResult、err
|
||||
setResult, err := s.longLoginRequest(ctx, state, &status)
|
||||
if err != nil {
|
||||
return setResult, err
|
||||
}
|
||||
// 官网 SET 成功后触发 LONG_LOGIN_SWITCH,再通过 QUERY 获取最终状态;SET
|
||||
// 本身只要求 data.success,不要求携带 returnValue。
|
||||
// queried、err 用于本次流程后续判断的queried、err
|
||||
queried, err := s.longLoginRequest(ctx, state, nil)
|
||||
if queried == nil {
|
||||
queried = &LongLoginSettings{
|
||||
Enabled: enabled,
|
||||
}
|
||||
state.populate(queried)
|
||||
}
|
||||
queried.SetCookies = append(append([]string(nil), setResult.SetCookies...), queried.SetCookies...)
|
||||
if err != nil {
|
||||
// QUERY 失败时仍返回 SET 请求及 QUERY 响应头已经刷新的 Cookie;最终
|
||||
// 开关状态尚未确认,只能保留调用方本次请求的目标值。
|
||||
queried.Enabled = enabled
|
||||
return queried, err
|
||||
}
|
||||
return queried, nil
|
||||
}
|
||||
|
||||
// longLoginRequest 封装long登录请求业务协调。
|
||||
func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCookieState, status *string) (*LongLoginSettings, error) {
|
||||
// partial 用于本次流程后续判断的partial
|
||||
partial := &LongLoginSettings{}
|
||||
cookieState.populate(partial)
|
||||
if status != nil {
|
||||
partial.Enabled = *status == "0"
|
||||
}
|
||||
// cookieURL 用于本次流程后续判断的登录凭证URL
|
||||
cookieURL := QueryLoginSettingsURL
|
||||
// target 用于本次流程后续判断的target
|
||||
target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
|
||||
// body 用于本次流程后续判断的请求体
|
||||
var body io.Reader
|
||||
if status != nil {
|
||||
cookieURL = SetLoginSettingsURL
|
||||
target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
|
||||
body = strings.NewReader("status=" + url.QueryEscape(*status))
|
||||
}
|
||||
// req、err 用于本次流程后续判断的req、err
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
|
||||
if err != nil {
|
||||
return partial, err
|
||||
}
|
||||
appendOrderedQuery(req.URL, [][2]string{{"fromSite", "77"}, {"appName", "xianyu"}, {"bizEntrance", "web"}})
|
||||
setSilentHasLoginHeaders(req, cookieState.requestCookies(cookieURL), s.documentReferer())
|
||||
if status != nil {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
// hc 用于本次流程后续判断的hc
|
||||
hc := s.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: longLoginRequestTimout}
|
||||
}
|
||||
// requestCtx、cancel 用于本次流程后续判断的请求Ctx、cancel
|
||||
requestCtx, cancel := context.WithTimeout(req.Context(), longLoginRequestTimout)
|
||||
defer cancel()
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := hc.Do(req.Clone(requestCtx))
|
||||
if err != nil {
|
||||
return partial, fmt.Errorf("保存登录信息请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// 浏览器在响应头到达时就会更新 Cookie Jar;因此必须先捕获 Set-Cookie,
|
||||
// 即使随后读取响应体、校验 HTTP 状态或解析业务 JSON 失败也要返回给调用方。
|
||||
partial.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
|
||||
cookieState.apply(cookieURL, partial.SetCookies)
|
||||
cookieState.populate(partial)
|
||||
// raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := readRenewBody(resp.Body)
|
||||
if err != nil {
|
||||
return partial, fmt.Errorf("保存登录信息响应读取失败: %w", err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return partial, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
|
||||
}
|
||||
if status != nil {
|
||||
if !longLoginSetBusinessOK(raw) {
|
||||
return partial, fmt.Errorf("保存登录信息业务结果未确认成功")
|
||||
}
|
||||
return partial, nil
|
||||
}
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := findReturnValue(raw)
|
||||
if !ok {
|
||||
return partial, fmt.Errorf("保存登录信息响应缺少 returnValue")
|
||||
}
|
||||
partial.CanOpenLongLogin, _ = value["canOpenLongLogin"].(bool)
|
||||
partial.Enabled, _ = value["hasLongTokenLogin"].(bool)
|
||||
return partial, nil
|
||||
}
|
||||
|
||||
// longLoginSetBusinessOK 封装long登录SetBusinessOK业务协调。
|
||||
func longLoginSetBusinessOK(raw []byte) bool {
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return false
|
||||
}
|
||||
if // success 用于本次流程后续判断的success
|
||||
success, _ := payload["success"].(bool); success {
|
||||
return true
|
||||
}
|
||||
if // data 用于本次流程后续判断的数据
|
||||
data, _ := payload["data"].(map[string]any); data != nil {
|
||||
// success 用于本次流程后续判断的success
|
||||
success, _ := data["success"].(bool)
|
||||
return success
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// findReturnValue 封装findReturn值业务协调。
|
||||
func findReturnValue(raw []byte) (map[string]any, bool) {
|
||||
// payload 用于本次流程后续判断的请求载荷
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, false
|
||||
}
|
||||
return findMapChild(payload, "returnValue", 0)
|
||||
}
|
||||
|
||||
// findMapChild 封装findMapChild业务协调。
|
||||
func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) {
|
||||
if parent == nil || depth > 6 {
|
||||
return nil, false
|
||||
}
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := parent[key].(map[string]any); ok {
|
||||
return value, true
|
||||
}
|
||||
// child 表示当前遍历过程中的child
|
||||
for _, child := range parent {
|
||||
if // nested、ok 用于本次流程后续判断的nested、ok
|
||||
nested, ok := child.(map[string]any); ok {
|
||||
if // value、found 用于本次流程后续判断的value、found
|
||||
value, found := findMapChild(nested, key, depth+1); found {
|
||||
return value, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Result 描述一次接口续期的完整结果。
|
||||
type Result struct {
|
||||
Success bool
|
||||
|
||||
@@ -3,7 +3,6 @@ package ws
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -768,256 +767,3 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
|
||||
}
|
||||
|
||||
// handleSyncExtra 封装handleSyncExtra业务协调。
|
||||
func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
// extra 用于本次流程后续判断的extra
|
||||
extra, _ := body["syncExtraType"].(map[string]any)
|
||||
// typeCode、ok 用于本次流程后续判断的类型Code、ok
|
||||
typeCode, ok := responseCode(extra["type"])
|
||||
if !ok || (typeCode != 1 && typeCode != 2) {
|
||||
return nil
|
||||
}
|
||||
// state、err 用于本次流程后续判断的state、err
|
||||
state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getState: %w", err)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
|
||||
return fmt.Errorf("getState 返回异常: code=%v", state["code"])
|
||||
}
|
||||
// response、err 用于本次流程后续判断的response、err
|
||||
response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ackDiff: %w", err)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return fmt.Errorf("ackDiff 返回异常: code=%d", code)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。
|
||||
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
|
||||
// headers 用于本次流程后续判断的headers
|
||||
headers, _ := msg["headers"].(map[string]any)
|
||||
// ackHeaders 用于本次流程后续判断的ackHeaders
|
||||
ackHeaders := make(map[string]any, len(headers))
|
||||
// key、value 表示当前遍历过程中的key、value
|
||||
for key, value := range headers {
|
||||
ackHeaders[key] = value
|
||||
}
|
||||
// ack 用于本次流程后续判断的ack
|
||||
ack := map[string]any{
|
||||
"code": 200,
|
||||
"headers": ackHeaders,
|
||||
}
|
||||
// ACK 失败不阻塞主循环。
|
||||
ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
_ = c.sendJSON(ackCtx, ack)
|
||||
cancel()
|
||||
}
|
||||
|
||||
// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。
|
||||
func extractSyncPayload(msg map[string]any) (string, bool) {
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
if body == nil {
|
||||
return "", false
|
||||
}
|
||||
// pkg 用于本次流程后续判断的pkg
|
||||
pkg, _ := body["syncPushPackage"].(map[string]any)
|
||||
if pkg == nil {
|
||||
return "", false
|
||||
}
|
||||
// arr 用于本次流程后续判断的arr
|
||||
arr, _ := pkg["data"].([]any)
|
||||
if len(arr) == 0 {
|
||||
return "", false
|
||||
}
|
||||
// first 用于本次流程后续判断的first
|
||||
first, _ := arr[0].(map[string]any)
|
||||
if first == nil {
|
||||
return "", false
|
||||
}
|
||||
// d、ok 用于本次流程后续判断的d、ok
|
||||
d, ok := first["data"].(string)
|
||||
return d, ok && d != ""
|
||||
}
|
||||
|
||||
// decodeSyncData 先尝试 base64+JSON(未加密系统消息),失败则 base64+msgpack 解密。
|
||||
func decodeSyncData(data string) (map[string]any, error) {
|
||||
// 1) base64 解码后尝试解析 JSON。
|
||||
if dec, err := base64.StdEncoding.DecodeString(data); err == nil {
|
||||
// parsed 用于本次流程后续判断的解析结果
|
||||
var parsed map[string]any
|
||||
if // jsonErr 用于本次流程后续判断的jsonErr
|
||||
jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
// 2) JSON 解析失败 → msgpack 解密
|
||||
out, err := protocol.Decrypt(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// parsed 用于本次流程后续判断的解析结果
|
||||
var parsed map[string]any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(out), &parsed); err != nil {
|
||||
return nil, fmt.Errorf("解密后非 JSON: %w", err)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// sendJSON 发送一条 JSON 文本帧。
|
||||
func (c *Conn) sendJSON(ctx context.Context, v any) error {
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // recorder 用于本次流程后续判断的recorder
|
||||
recorder := c.recorderSnapshot(); recorder != nil {
|
||||
recorder("out", string(b), string(b), "json", "")
|
||||
}
|
||||
select {
|
||||
case c.sendGate <- struct{}{}:
|
||||
defer func() { <-c.sendGate }()
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
return c.ws.Write(ctx, websocket.MessageText, b)
|
||||
}
|
||||
|
||||
// SendText 发送一条闲鱼聊天文本消息。
|
||||
func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error {
|
||||
// content 用于本次流程后续判断的内容
|
||||
content := map[string]any{
|
||||
"contentType": 1,
|
||||
"text": map[string]any{
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// MarkChatRead 将当前会话的 PNM 消息 ID 上报为已读。
|
||||
// ctx 控制远端请求生命周期;cid 仅用于本地可观测日志;messageIDs 为待上报消息对象。
|
||||
// 返回值仅报告远端调用失败,平台拒绝会被记录为告警以保留既有调用兼容性。
|
||||
func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error {
|
||||
// ids 是剔除空值后的 PNM ID 列表,按平台 MessageStatusService 的参数格式发送。
|
||||
ids := make([]string, 0, len(messageIDs))
|
||||
// item 为调用方传入的一条待读消息对象,可能缺少平台消息 ID。
|
||||
for _, item := range messageIDs {
|
||||
// id 是当前对象中可上报的非空 PNM 消息 ID。
|
||||
if id := strings.TrimSpace(fmt.Sprint(item["messageId"])); id != "" && id != "<nil>" {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
c.logger.Info("准备上报闲鱼已读", "cid", cid, "message_count", len(ids), "message_ids", ids)
|
||||
// response 保存平台响应;err 表示请求或传输失败。服务只接受一个 string 列表参数。
|
||||
response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout)
|
||||
if err == nil {
|
||||
// code 是平台业务状态码;ok 表示响应中的状态码可被规范解析。
|
||||
if code, ok := responseCode(response["code"]); ok && code >= 400 {
|
||||
c.logger.Warn("闲鱼已读上报被拒绝", "cid", cid, "message_count", len(ids), "code", code, "body", response["body"])
|
||||
} else {
|
||||
c.logger.Info("闲鱼已读上报成功", "cid", cid, "message_count", len(ids), "message_ids", ids, "code", response["code"])
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。
|
||||
func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error {
|
||||
if width <= 0 {
|
||||
width = 800
|
||||
}
|
||||
if height <= 0 {
|
||||
height = 600
|
||||
}
|
||||
// content 用于本次流程后续判断的内容
|
||||
content := map[string]any{
|
||||
"contentType": 2,
|
||||
"image": map[string]any{
|
||||
"pics": []map[string]any{{
|
||||
"height": height,
|
||||
"type": 0,
|
||||
"url": imageURL,
|
||||
"width": width,
|
||||
}},
|
||||
},
|
||||
}
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// sendChatContent 封装send聊天内容业务协调。
|
||||
func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, content any) error {
|
||||
myID = stripGoofish(myID)
|
||||
cid = stripGoofish(cid)
|
||||
toID = stripGoofish(toID)
|
||||
if myID == "" || cid == "" || toID == "" {
|
||||
return fmt.Errorf("发送消息缺少必要参数: myID=%q cid=%q toID=%q", myID, cid, toID)
|
||||
}
|
||||
// raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// encoded 用于本次流程后续判断的encoded
|
||||
encoded := base64.StdEncoding.EncodeToString(raw)
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := map[string]any{
|
||||
"lwp": "/r/MessageSend/sendByReceiverScope",
|
||||
"headers": map[string]any{
|
||||
"mid": protocol.GenerateMid(),
|
||||
},
|
||||
"body": []any{
|
||||
map[string]any{
|
||||
"uuid": protocol.GenerateUUID(),
|
||||
"cid": cid + "@goofish",
|
||||
"conversationType": 1,
|
||||
"content": map[string]any{
|
||||
"contentType": 101,
|
||||
"custom": map[string]any{
|
||||
"type": 1,
|
||||
"data": encoded,
|
||||
},
|
||||
},
|
||||
"redPointPolicy": 0,
|
||||
"extension": map[string]any{
|
||||
"extJson": "{}",
|
||||
},
|
||||
"ctx": map[string]any{
|
||||
"appVersion": "1.0",
|
||||
"platform": "web",
|
||||
},
|
||||
"mtags": map[string]any{},
|
||||
"msgReadStatusSetting": 1,
|
||||
},
|
||||
map[string]any{
|
||||
"actualReceivers": []string{
|
||||
toID + "@goofish",
|
||||
myID + "@goofish",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
return c.sendJSON(ctx, msg)
|
||||
}
|
||||
|
||||
// stripGoofish 封装stripGoofish业务协调。
|
||||
func stripGoofish(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
return strings.TrimSuffix(s, "@goofish")
|
||||
}
|
||||
|
||||
// Close 关闭连接。
|
||||
func (c *Conn) Close() error {
|
||||
c.ensureReadPump()
|
||||
c.readCancel()
|
||||
return c.ws.Close(websocket.StatusNormalClosure, "bye")
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// handleSyncExtra 处理服务端增量同步帧并在需要时回传确认,返回解码或发送错误。
|
||||
func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
// extra 用于本次流程后续判断的extra
|
||||
extra, _ := body["syncExtraType"].(map[string]any)
|
||||
// typeCode、ok 用于本次流程后续判断的类型Code、ok
|
||||
typeCode, ok := responseCode(extra["type"])
|
||||
if !ok || (typeCode != 1 && typeCode != 2) {
|
||||
return nil
|
||||
}
|
||||
// state、err 用于本次流程后续判断的state、err
|
||||
state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getState: %w", err)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
|
||||
return fmt.Errorf("getState 返回异常: code=%v", state["code"])
|
||||
}
|
||||
// response、err 用于本次流程后续判断的response、err
|
||||
response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ackDiff: %w", err)
|
||||
}
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return fmt.Errorf("ackDiff 返回异常: code=%d", code)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。
|
||||
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
|
||||
// headers 用于本次流程后续判断的headers
|
||||
headers, _ := msg["headers"].(map[string]any)
|
||||
// ackHeaders 用于本次流程后续判断的ackHeaders
|
||||
ackHeaders := make(map[string]any, len(headers))
|
||||
// key、value 表示当前遍历过程中的key、value
|
||||
for key, value := range headers {
|
||||
ackHeaders[key] = value
|
||||
}
|
||||
// ack 用于本次流程后续判断的ack
|
||||
ack := map[string]any{
|
||||
"code": 200,
|
||||
"headers": ackHeaders,
|
||||
}
|
||||
// ACK 失败不阻塞主循环。
|
||||
ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
_ = c.sendJSON(ackCtx, ack)
|
||||
cancel()
|
||||
}
|
||||
|
||||
// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。
|
||||
func extractSyncPayload(msg map[string]any) (string, bool) {
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body, _ := msg["body"].(map[string]any)
|
||||
if body == nil {
|
||||
return "", false
|
||||
}
|
||||
// pkg 用于本次流程后续判断的pkg
|
||||
pkg, _ := body["syncPushPackage"].(map[string]any)
|
||||
if pkg == nil {
|
||||
return "", false
|
||||
}
|
||||
// arr 用于本次流程后续判断的arr
|
||||
arr, _ := pkg["data"].([]any)
|
||||
if len(arr) == 0 {
|
||||
return "", false
|
||||
}
|
||||
// first 用于本次流程后续判断的first
|
||||
first, _ := arr[0].(map[string]any)
|
||||
if first == nil {
|
||||
return "", false
|
||||
}
|
||||
// d、ok 用于本次流程后续判断的d、ok
|
||||
d, ok := first["data"].(string)
|
||||
return d, ok && d != ""
|
||||
}
|
||||
|
||||
// decodeSyncData 先尝试 base64+JSON(未加密系统消息),失败则 base64+msgpack 解密。
|
||||
func decodeSyncData(data string) (map[string]any, error) {
|
||||
// 1) base64 解码后尝试解析 JSON。
|
||||
if dec, err := base64.StdEncoding.DecodeString(data); err == nil {
|
||||
// parsed 用于本次流程后续判断的解析结果
|
||||
var parsed map[string]any
|
||||
if // jsonErr 用于本次流程后续判断的jsonErr
|
||||
jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
// 2) JSON 解析失败 → msgpack 解密
|
||||
out, err := protocol.Decrypt(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// parsed 用于本次流程后续判断的解析结果
|
||||
var parsed map[string]any
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := json.Unmarshal([]byte(out), &parsed); err != nil {
|
||||
return nil, fmt.Errorf("解密后非 JSON: %w", err)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// sendJSON 发送一条 JSON 文本帧。
|
||||
func (c *Conn) sendJSON(ctx context.Context, v any) error {
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // recorder 用于本次流程后续判断的recorder
|
||||
recorder := c.recorderSnapshot(); recorder != nil {
|
||||
recorder("out", string(b), string(b), "json", "")
|
||||
}
|
||||
select {
|
||||
case c.sendGate <- struct{}{}:
|
||||
defer func() { <-c.sendGate }()
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
return c.ws.Write(ctx, websocket.MessageText, b)
|
||||
}
|
||||
|
||||
// SendText 发送一条闲鱼聊天文本消息。
|
||||
func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error {
|
||||
// content 用于本次流程后续判断的内容
|
||||
content := map[string]any{
|
||||
"contentType": 1,
|
||||
"text": map[string]any{
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// MarkChatRead 将当前会话的 PNM 消息 ID 上报为已读。
|
||||
// ctx 控制远端请求生命周期;cid 仅用于本地可观测日志;messageIDs 为待上报消息对象。
|
||||
// 返回值仅报告远端调用失败,平台拒绝会被记录为告警以保留既有调用兼容性。
|
||||
func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error {
|
||||
// ids 是剔除空值后的 PNM ID 列表,按平台 MessageStatusService 的参数格式发送。
|
||||
ids := make([]string, 0, len(messageIDs))
|
||||
// item 为调用方传入的一条待读消息对象,可能缺少平台消息 ID。
|
||||
for _, item := range messageIDs {
|
||||
// id 是当前对象中可上报的非空 PNM 消息 ID。
|
||||
if id := strings.TrimSpace(fmt.Sprint(item["messageId"])); id != "" && id != "<nil>" {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
c.logger.Info("准备上报闲鱼已读", "cid", cid, "message_count", len(ids), "message_ids", ids)
|
||||
// response 保存平台响应;err 表示请求或传输失败。服务只接受一个 string 列表参数。
|
||||
response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout)
|
||||
if err == nil {
|
||||
// code 是平台业务状态码;ok 表示响应中的状态码可被规范解析。
|
||||
if code, ok := responseCode(response["code"]); ok && code >= 400 {
|
||||
c.logger.Warn("闲鱼已读上报被拒绝", "cid", cid, "message_count", len(ids), "code", code, "body", response["body"])
|
||||
} else {
|
||||
c.logger.Info("闲鱼已读上报成功", "cid", cid, "message_count", len(ids), "message_ids", ids, "code", response["code"])
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。
|
||||
func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error {
|
||||
if width <= 0 {
|
||||
width = 800
|
||||
}
|
||||
if height <= 0 {
|
||||
height = 600
|
||||
}
|
||||
// content 用于本次流程后续判断的内容
|
||||
content := map[string]any{
|
||||
"contentType": 2,
|
||||
"image": map[string]any{
|
||||
"pics": []map[string]any{{
|
||||
"height": height,
|
||||
"type": 0,
|
||||
"url": imageURL,
|
||||
"width": width,
|
||||
}},
|
||||
},
|
||||
}
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// sendChatContent 封装send聊天内容业务协调。
|
||||
func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, content any) error {
|
||||
myID = stripGoofish(myID)
|
||||
cid = stripGoofish(cid)
|
||||
toID = stripGoofish(toID)
|
||||
if myID == "" || cid == "" || toID == "" {
|
||||
return fmt.Errorf("发送消息缺少必要参数: myID=%q cid=%q toID=%q", myID, cid, toID)
|
||||
}
|
||||
// raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// encoded 用于本次流程后续判断的encoded
|
||||
encoded := base64.StdEncoding.EncodeToString(raw)
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := map[string]any{
|
||||
"lwp": "/r/MessageSend/sendByReceiverScope",
|
||||
"headers": map[string]any{
|
||||
"mid": protocol.GenerateMid(),
|
||||
},
|
||||
"body": []any{
|
||||
map[string]any{
|
||||
"uuid": protocol.GenerateUUID(),
|
||||
"cid": cid + "@goofish",
|
||||
"conversationType": 1,
|
||||
"content": map[string]any{
|
||||
"contentType": 101,
|
||||
"custom": map[string]any{
|
||||
"type": 1,
|
||||
"data": encoded,
|
||||
},
|
||||
},
|
||||
"redPointPolicy": 0,
|
||||
"extension": map[string]any{
|
||||
"extJson": "{}",
|
||||
},
|
||||
"ctx": map[string]any{
|
||||
"appVersion": "1.0",
|
||||
"platform": "web",
|
||||
},
|
||||
"mtags": map[string]any{},
|
||||
"msgReadStatusSetting": 1,
|
||||
},
|
||||
map[string]any{
|
||||
"actualReceivers": []string{
|
||||
toID + "@goofish",
|
||||
myID + "@goofish",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
return c.sendJSON(ctx, msg)
|
||||
}
|
||||
|
||||
// stripGoofish 封装stripGoofish业务协调。
|
||||
func stripGoofish(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
return strings.TrimSuffix(s, "@goofish")
|
||||
}
|
||||
|
||||
// Close 关闭连接。
|
||||
func (c *Conn) Close() error {
|
||||
c.ensureReadPump()
|
||||
c.readCancel()
|
||||
return c.ws.Close(websocket.StatusNormalClosure, "bye")
|
||||
}
|
||||
@@ -252,817 +252,3 @@ func importsCompositionPath(syntax *ast.File) bool {
|
||||
}
|
||||
|
||||
// checkStageTwoTransportBoundary 以 fail-closed 规则阻止组合根、平台实现和生命周期所有权重新进入 Server。
|
||||
func checkStageTwoTransportBoundary(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// isServer 表示当前文件是否属于 HTTP transport 包。
|
||||
isServer := strings.HasPrefix(normalizedPath, "internal/server/")
|
||||
// isServerCommand 表示当前文件是否属于 Server 进程入口包。
|
||||
isServerCommand := strings.HasPrefix(normalizedPath, "cmd/server/")
|
||||
if !isServer && !isServerCommand {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前源码文件违反阶段二边界的全部位置。
|
||||
var violations []violation
|
||||
if isServer && filepath.Base(normalizedPath) == "application_services.go" {
|
||||
violations = append(violations, violation{file: normalizedPath, line: 1, message: "阶段二禁止 internal/server/application_services.go;应用服务、runner 和 coordinator 必须迁入 composition 与应用层"})
|
||||
}
|
||||
// forbiddenImports 是当前阶段不允许出现在 transport 或 cmd 组合入口的跨层依赖。
|
||||
var forbiddenImports map[string]string
|
||||
if isServer {
|
||||
forbiddenImports = map[string]string{
|
||||
"internal/account": "Server 不得直接依赖 account.Manager,必须消费应用 Port",
|
||||
"internal/adapter": "Server 不得直接依赖 adapter 实现或 factory,必须消费应用 Port",
|
||||
"internal/automation": "Server 不得直接依赖 automation.Center,必须消费应用 Port",
|
||||
"internal/browser": "Server 不得直接依赖 browser 实现,必须消费应用 Port",
|
||||
"internal/chat": "Server 不得直接依赖 chat.Service,必须消费聊天应用 Port",
|
||||
"internal/db": "Server 不得直接依赖 db.Store 或 repository,实现必须留在 adapter",
|
||||
"internal/notify": "Server 不得直接依赖 notifier,实现必须留在通知应用 Port",
|
||||
"internal/xianyu": "Server 不得直接依赖平台协议,实现必须留在 adapter",
|
||||
}
|
||||
} else {
|
||||
forbiddenImports = map[string]string{
|
||||
"internal/adapter": "cmd/server 不得直接装配 adapter 服务;必须委托 internal/composition",
|
||||
"internal/account": "cmd/server 不得直接装配账号运行时;必须委托 internal/composition",
|
||||
"internal/automation": "cmd/server 不得直接装配自动化 worker;必须委托 internal/composition",
|
||||
"internal/chat": "cmd/server 不得直接装配聊天服务;必须委托 internal/composition",
|
||||
"internal/notify": "cmd/server 不得直接装配通知 worker;必须委托 internal/composition",
|
||||
"internal/application/": "cmd/server 不得直接构造应用服务或 worker;必须委托 internal/composition",
|
||||
}
|
||||
}
|
||||
// imported 是当前源码声明的内部或标准库导入,必须逐项检查其是否越过当前层边界。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是去除模块前缀后的稳定内部导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
// forbiddenPath 是禁止导入的内部路径前缀;message 是命中后返回给迁移者的具体修复方向。
|
||||
for forbiddenPath, message := range forbiddenImports {
|
||||
if importPath == forbiddenPath || strings.HasPrefix(importPath, forbiddenPath) {
|
||||
violations = append(violations, violation{file: normalizedPath, line: fset.Position(imported.Pos()).Line, message: message})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if isServer {
|
||||
violations = append(violations, checkStageTwoServerDeclarations(normalizedPath, syntax, fset)...)
|
||||
violations = append(violations, checkStageTwoServerConstruction(normalizedPath, syntax, fset)...)
|
||||
violations = append(violations, checkStageTwoApplicationPortDeclarations(normalizedPath, syntax, fset)...)
|
||||
}
|
||||
violations = append(violations, checkStageTwoCompositionProjection(normalizedPath, syntax, fset)...)
|
||||
if isServerCommand {
|
||||
violations = append(violations, checkStageTwoCmdCalls(normalizedPath, syntax, fset)...)
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkStageTwoApplicationPortDeclarations 拒绝 HTTP Port 容器重新持有具体应用服务实现。
|
||||
func checkStageTwoApplicationPortDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if filepath.Base(relativePath) != "application_ports.go" {
|
||||
return nil
|
||||
}
|
||||
// applicationAliases 保存当前文件中应用包的本地导入别名。
|
||||
applicationAliases := applicationImportAliases(syntax)
|
||||
// violations 保存具体应用服务指针泄露到 transport Port 容器的全部位置。
|
||||
var violations []violation
|
||||
// declaration 是当前文件的顶级声明,只有类型声明可能定义 Port 容器。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// generalDeclaration、ok 分别是转换后的通用声明及其类型匹配状态。
|
||||
generalDeclaration, ok := declaration.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是该通用声明中的单个类型规格。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// typeSpecification、ok 分别是转换后的类型规格及其匹配状态。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok || (typeSpecification.Name.Name != "ApplicationPorts" && typeSpecification.Name.Name != "ApplicationPortsInput") {
|
||||
continue
|
||||
}
|
||||
// structure、ok 分别是 Port 容器的结构体定义及其类型匹配状态。
|
||||
structure, ok := typeSpecification.Type.(*ast.StructType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// field 是当前 Port 容器声明的字段,用于检查是否泄露具体应用服务。
|
||||
for _, field := range structure.Fields.List {
|
||||
if !containsConcreteApplicationServicePointer(field.Type, applicationAliases) {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(field.Pos()).Line, message: "阶段二 HTTP 应用 Port 容器不得持有具体 application Service 指针;请在 internal/server 定义消费者接口并由 composition 投影实现"})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// applicationImportAliases 收集 internal/application 子包的本地别名。
|
||||
func applicationImportAliases(syntax *ast.File) map[string]struct{} {
|
||||
// aliases 保存应用包在当前文件中的可见名称。
|
||||
aliases := make(map[string]struct{})
|
||||
// imported 是当前 transport 文件的导入项,用于识别应用包的本地别名。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是标准化后的仓库内导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
if !strings.HasPrefix(importPath, "internal/application/") {
|
||||
continue
|
||||
}
|
||||
// alias 是当前文件使用的应用包本地名称,默认取导入路径末段。
|
||||
alias := filepath.Base(importPath)
|
||||
if imported.Name != nil {
|
||||
alias = imported.Name.Name
|
||||
}
|
||||
if alias != "_" && alias != "." {
|
||||
aliases[alias] = struct{}{}
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
|
||||
// containsConcreteApplicationServicePointer 递归识别字段类型中隐藏的具体应用服务指针。
|
||||
func containsConcreteApplicationServicePointer(expression ast.Expr, applicationAliases map[string]struct{}) bool {
|
||||
// pointer 表示当前类型是否直接持有应用层对象;只有具体 Service/ServiceSet 才违反 Port 边界。
|
||||
if pointer, ok := expression.(*ast.StarExpr); ok {
|
||||
// selector、ok 分别是指针元素的限定类型选择器及其匹配状态。
|
||||
if selector, ok := pointer.X.(*ast.SelectorExpr); ok {
|
||||
// packageName、ok 分别是限定类型所属包标识符及其匹配状态。
|
||||
if packageName, ok := selector.X.(*ast.Ident); ok {
|
||||
// imported 表示该包名是否来自当前文件导入的应用层包。
|
||||
if _, imported := applicationAliases[packageName.Name]; imported && (strings.HasSuffix(selector.Sel.Name, "Service") || strings.HasSuffix(selector.Sel.Name, "ServiceSet")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return containsConcreteApplicationServicePointer(pointer.X, applicationAliases)
|
||||
}
|
||||
// array 表示切片或数组字段;递归避免以集合形式隐藏具体服务。
|
||||
if array, ok := expression.(*ast.ArrayType); ok {
|
||||
return containsConcreteApplicationServicePointer(array.Elt, applicationAliases)
|
||||
}
|
||||
// mapping 表示 map 字段;键和值都不能用于隐藏服务实例。
|
||||
if mapping, ok := expression.(*ast.MapType); ok {
|
||||
return containsConcreteApplicationServicePointer(mapping.Key, applicationAliases) || containsConcreteApplicationServicePointer(mapping.Value, applicationAliases)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkStageTwoCompositionProjection 确保 composition 核心不反向依赖 Server,只有 runtime 子层可以投影 Server 依赖。
|
||||
func checkStageTwoCompositionProjection(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if !strings.HasPrefix(relativePath, "internal/composition/") || strings.HasPrefix(relativePath, "internal/composition/runtime/") {
|
||||
return nil
|
||||
}
|
||||
// imported 是 composition 核心文件的导入项,核心层不得反向导入 Server。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil || normalizeImportPath(rawPath) != "internal/server" {
|
||||
continue
|
||||
}
|
||||
return []violation{{file: relativePath, line: fset.Position(imported.Pos()).Line, message: "阶段二 composition 核心不得依赖 Server;只能由 internal/composition/runtime 投影 server.Dependencies"}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkStageTwoServerDeclarations 禁止 Server 继续声明服务集合、平台 Port 或反向生命周期 API。
|
||||
func checkStageTwoServerDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// forbiddenTypes 是必须从 internal/server 消失的组合根和平台类型。
|
||||
forbiddenTypes := map[string]string{
|
||||
"ApplicationServices": "Server 不能拥有应用服务集合;请迁入 composition 并向 handler 注入最小应用 Port",
|
||||
"ApplicationServiceDependencies": "Server 不能声明应用服务装配依赖;请迁入 composition",
|
||||
"PlatformPort": "Server 不能持有 MTOP、长登录或二维码平台 Port;请迁入对应应用用例",
|
||||
}
|
||||
// forbiddenMethods 是必须从 Server 消失的反向访问器和 session callback。
|
||||
forbiddenMethods := map[string]string{
|
||||
"ApplicationServices": "Server 不得向外返还应用服务集合",
|
||||
"LifecycleComponents": "Server 不得生成或返还应用 worker 生命周期组件",
|
||||
"mtopClient": "Server 不得获取 MTOP 客户端",
|
||||
"longLoginClient": "Server 不得获取长登录客户端",
|
||||
"qrLoginService": "Server 不得获取二维码平台客户端",
|
||||
"sessionRecoveryCallback": "Server 不得创建 session recovery callback",
|
||||
"recoverExpiredMTOPSession": "Server 不得承载 MTOP session 恢复",
|
||||
}
|
||||
// violations 保存声明层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
// declaration 是当前 Server 文件的顶层声明,可能声明禁止的组合根类型或访问器。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// typedDeclaration 是顶层声明的具体语法类型,用于分开处理类型和函数声明。
|
||||
switch typedDeclaration := declaration.(type) {
|
||||
case *ast.GenDecl:
|
||||
if typedDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是当前类型声明块中的单个类型定义。
|
||||
for _, specification := range typedDeclaration.Specs {
|
||||
// typeSpecification、ok 分别是当前语法规格是否为具名类型及其断言结果。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// message、forbidden 分别是命中禁止类型时的修复提示及其匹配结果。
|
||||
if message, forbidden := forbiddenTypes[typeSpecification.Name.Name]; forbidden {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(typeSpecification.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
// message、forbidden 分别是命中禁止 Server 访问器时的修复提示及其匹配结果。
|
||||
if message, forbidden := forbiddenMethods[typedDeclaration.Name.Name]; forbidden {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(typedDeclaration.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkStageTwoServerConstruction 拒绝 Server 直接构造应用服务、runner、coordinator 或 adapter factory。
|
||||
func checkStageTwoServerConstruction(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// internalAliases 保存当前文件中指向 application 或 adapter 的导入别名,供构造调用精确判定。
|
||||
internalAliases := internalConstructionImportAliases(syntax)
|
||||
// violations 保存调用层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数或方法调用。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 表示当前调用的接收者与方法名称。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// name 是当前被调用的方法或构造函数名称。
|
||||
name := selector.Sel.Name
|
||||
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" || name == "sessionRecoveryCallback" || name == "recoverExpiredMTOPSession" || (strings.HasPrefix(name, "New") && isInternalConstructionCall(selector.X, internalAliases)) {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("Server 禁止调用 %s;应用服务、runner、coordinator 和 adapter factory 必须由 composition 构造", name)})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// internalConstructionImportAliases 收集 application 与 adapter 导入的本地别名,避免误判标准库 New 调用。
|
||||
func internalConstructionImportAliases(syntax *ast.File) map[string]struct{} {
|
||||
// aliases 保存需要受阶段二构造门禁保护的本地导入名。
|
||||
aliases := make(map[string]struct{})
|
||||
// imported 是当前待解析别名的导入声明。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是去除模块前缀后的内部导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
if !strings.HasPrefix(importPath, "internal/application/") && !strings.HasPrefix(importPath, "internal/adapter") {
|
||||
continue
|
||||
}
|
||||
// alias 是源码调用选择器使用的包名;显式别名优先于路径末段。
|
||||
alias := filepath.Base(importPath)
|
||||
if imported.Name != nil {
|
||||
alias = imported.Name.Name
|
||||
}
|
||||
if alias != "_" && alias != "." {
|
||||
aliases[alias] = struct{}{}
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
|
||||
// isInternalConstructionCall 判断构造调用是否来自应用/adapter 包或依赖 factory 链。
|
||||
func isInternalConstructionCall(receiver ast.Expr, internalAliases map[string]struct{}) bool {
|
||||
// identifier 是直接包名调用,例如 orderapp.NewRefreshJobRunner。
|
||||
if identifier, ok := receiver.(*ast.Ident); ok {
|
||||
// found 表示该直接接收者是否是 application 或 adapter 的本地导入别名。
|
||||
_, found := internalAliases[identifier.Name]
|
||||
return found
|
||||
}
|
||||
// selector 表示依赖 factory 链,例如 dependencies.ItemDependencies.NewItemBatchRepository。
|
||||
_, isFactoryChain := receiver.(*ast.SelectorExpr)
|
||||
return isFactoryChain
|
||||
}
|
||||
|
||||
// checkStageTwoCmdCalls 拒绝 cmd/server 通过 Server API 或 factory 间接重新承担业务组合根职责。
|
||||
func checkStageTwoCmdCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// violations 保存入口层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数或方法调用。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 表示当前调用的接收者与名称。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// name 是被调用的构造或生命周期访问器名称。
|
||||
name := selector.Sel.Name
|
||||
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("cmd/server 禁止通过 %s 使用 Server 组合根;必须调用 internal/composition", name)})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkServerInfrastructureFields 禁止 HTTP Server 保存业务运行时或具体平台实现,避免 transport 成为组合根。
|
||||
func checkServerInfrastructureFields(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// forbiddenTypes 记录 Server 不得作为字段持有者的业务运行时和平台实现类型。
|
||||
forbiddenTypes := map[string]string{
|
||||
"account.Manager": "账号 Manager 必须由进程组合根和应用 Port 持有,Server 只能调用应用服务",
|
||||
"automation.Center": "自动化 Center 必须由应用层持有,Server 不能保存业务 worker",
|
||||
"notify.Notifier": "通知器必须通过通知应用 Port 使用,Server 不能保存基础设施实现",
|
||||
"adapter.PlatformDependencies": "具体平台依赖必须在组合根封装为消费者定义的 Port",
|
||||
"adapter.MTOPClient": "MTOP 客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
"adapter.LongLoginClient": "长登录客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
"adapter.QRLoginService": "二维码客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
}
|
||||
// violations 保存 Server 结构体字段违反基础设施持有边界的扫描结果。
|
||||
var violations []violation
|
||||
// declaration 是当前文件中的类型声明,只有 Server 结构体需要本规则检查。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// generalDeclaration 表示可能包含类型定义的声明。
|
||||
generalDeclaration, ok := declaration.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是当前声明中的一个类型定义。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// typeSpecification 表示具体类型名及其语法树。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok || typeSpecification.Name.Name != "Server" {
|
||||
continue
|
||||
}
|
||||
// structure 表示 Server 的字段集合;非结构体类型不适用本规则。
|
||||
structure, ok := typeSpecification.Type.(*ast.StructType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// field 是当前待检查的 Server 字段。
|
||||
for _, field := range structure.Fields.List {
|
||||
// typeName 是去掉指针层后的限定类型名;未知表达式保持空字符串。
|
||||
typeName := qualifiedTypeName(field.Type)
|
||||
// message、forbidden 分别表示字段类型的禁止原因及其是否命中。
|
||||
message, forbidden := forbiddenTypes[typeName]
|
||||
if !forbidden {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{file: normalizedPath, line: fset.Position(field.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// qualifiedTypeName 返回指针、选择器或标识符类型的稳定文本名,供结构体字段边界规则使用。
|
||||
func qualifiedTypeName(expression ast.Expr) string {
|
||||
// pointer 表示字段是否以指针形式声明;边界规则不区分值与指针持有。
|
||||
if pointer, ok := expression.(*ast.StarExpr); ok {
|
||||
return qualifiedTypeName(pointer.X)
|
||||
}
|
||||
// selector 表示包限定类型,例如 adapter.MTOPClient。
|
||||
if selector, ok := expression.(*ast.SelectorExpr); ok {
|
||||
// packageName、ok 分别表示选择器左侧是否为可解析的包标识符。
|
||||
packageName, ok := selector.X.(*ast.Ident)
|
||||
if ok {
|
||||
return packageName.Name + "." + selector.Sel.Name
|
||||
}
|
||||
}
|
||||
// identifier 表示当前字段是否为未限定类型;本规则当前不禁止未限定类型。
|
||||
if identifier, ok := expression.(*ast.Ident); ok {
|
||||
return identifier.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// checkServerCompositionCalls 禁止已迁出的应用 worker 组合逻辑回流到 Server transport 包。
|
||||
func checkServerCompositionCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// forbiddenConstructors 记录必须由进程组合根创建的应用 worker 构造函数及修复提示。
|
||||
forbiddenConstructors := map[string]string{
|
||||
"NewReconciliationRecoveryCoordinator": "订单补偿恢复协调器必须由 cmd 组合根构造后注入 Server",
|
||||
"NewDatabaseHealth": "数据库健康检查端口必须由 cmd 组合根构造后注入 Server",
|
||||
}
|
||||
// forbiddenMethods 记录 Server 不得再作为应用 worker 生命周期反向提供者的遗留方法。
|
||||
forbiddenMethods := map[string]string{
|
||||
"ApplicationLifecycleComponents": "应用 worker 生命周期组件必须由组合根的应用服务集合登记,Server 不得反向返还组件",
|
||||
}
|
||||
// violations 保存当前 Server 文件中发现的组合根回流问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是包函数或对象方法调用;仅包级构造函数可能违反本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// message 是命中构造函数或遗留生命周期方法后返回的组合根迁移提示。
|
||||
message, forbidden := forbiddenConstructors[selector.Sel.Name]
|
||||
if !forbidden {
|
||||
message, forbidden = forbiddenMethods[selector.Sel.Name]
|
||||
}
|
||||
if forbidden {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: message,
|
||||
})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPRequestContracts 禁止 Server handler 使用匿名请求结构,保证请求契约能够被复用、审计和版本化。
|
||||
func checkHTTPRequestContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") || !strings.HasSuffix(normalizedPath, "_handlers.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 handler 文件中发现的匿名请求结构。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// declaration 是函数体内可能包含请求变量的声明语句。
|
||||
declaration, ok := node.(*ast.DeclStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// generalDeclaration 是具体的 var 声明;短变量声明不会承载匿名 struct 类型。
|
||||
generalDeclaration, ok := declaration.Decl.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.VAR {
|
||||
return true
|
||||
}
|
||||
// specification 是当前 var 声明中的单个语法规格。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// valueSpecification 是当前 var 声明的名称、类型和初始值组合。
|
||||
valueSpecification, ok := specification.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// anonymousStruct 表示该变量是否直接声明为匿名 struct 类型。
|
||||
_, anonymousStruct := valueSpecification.Type.(*ast.StructType)
|
||||
if !anonymousStruct {
|
||||
continue
|
||||
}
|
||||
// name 是当前匿名结构声明中的变量名。
|
||||
for _, name := range valueSpecification.Names {
|
||||
if name.Name != "req" && name.Name != "input" {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(valueSpecification.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 请求变量 %s 禁止使用匿名 struct,请定义具名 DTO", name.Name),
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkRuntimeSetterCalls 禁止生产代码调用仅为测试替身保留的 Adapter 运行时 setter。
|
||||
func checkRuntimeSetterCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// testOnlySetters 是已登记为测试隔离入口的 Adapter setter 名称。
|
||||
testOnlySetters := map[string]struct{}{
|
||||
"SetAutomation": {}, "SetNotifier": {}, "SetChatService": {}, "SetCredentialWakeService": {},
|
||||
"SetBrowser": {}, "SetRenewService": {}, "SetTokenCaptchaRequester": {}, "SetOrderDetailClient": {},
|
||||
}
|
||||
// violations 保存生产代码绕过构造期依赖固定的调用位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待判断的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是当前调用的选择器表达式,只有明确的 Adapter setter 名称才属于本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// registered 表示当前调用是否属于明确登记的测试兼容 setter。
|
||||
if _, registered := testOnlySetters[selector.Sel.Name]; !registered {
|
||||
return true
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: fmt.Sprintf("生产代码禁止调用测试兼容 setter %s,请通过构造期 RuntimeBundle 注入", selector.Sel.Name),
|
||||
})
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPResponseContracts 检查 Server 对外响应是否使用具名 DTO,并阻止动态 map 绕过契约边界。
|
||||
func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 Server 文件发现的 HTTP 契约问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// typedNode 是当前遍历到的 AST 节点,用于识别 HTTP 契约声明或调用。
|
||||
switch typedNode := node.(type) {
|
||||
case *ast.TypeSpec:
|
||||
if !isHTTPContractTypeName(typedNode.Name.Name) {
|
||||
return true
|
||||
}
|
||||
if (typedNode.Name.Name == "settingsResponse" || containsDynamicMapType(typedNode.Type)) &&
|
||||
!isControlledDynamicResponseType(typedNode.Name.Name) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(typedNode.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 契约类型 %s 禁止使用动态 map,请定义具名 DTO 字段", typedNode.Name.Name),
|
||||
})
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if !isWriteJSONCall(typedNode) || len(typedNode.Args) < 3 {
|
||||
return true
|
||||
}
|
||||
// responseArg 是 writeJSON 的响应值参数,必须是具名 DTO 或受控类型。
|
||||
responseArg := typedNode.Args[2]
|
||||
if isDynamicMapLiteral(responseArg) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(responseArg.Pos()).Line,
|
||||
message: "HTTP 响应禁止直接写入动态 map,请使用具名 DTO",
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免在未满足 Sunset 条件前改变旧客户端 JSON 形状。
|
||||
func isControlledDynamicResponseType(name string) bool {
|
||||
// ok 表示响应类型是否已在带 Sunset 条件的兼容登记表中备案。
|
||||
_, ok := controlledDynamicResponses[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// isForbiddenHiddenDependencyImport 禁止应用与 Server 通过反射、插件机制或动态加载隐藏必需依赖。
|
||||
func isForbiddenHiddenDependencyImport(filePath, importedPath string) bool {
|
||||
// productionLayer 表示必须封死隐式装配旁路的生产层。
|
||||
productionLayer := (strings.HasPrefix(filePath, "internal/application/") && !strings.HasSuffix(filePath, "_test.go")) ||
|
||||
(strings.HasPrefix(filePath, "internal/server/") && !strings.HasSuffix(filePath, "_test.go"))
|
||||
if !productionLayer {
|
||||
return false
|
||||
}
|
||||
for _, forbidden /* forbidden 是禁止隐藏依赖实现的标准库或运行时包名。 */ := range []string{"reflect", "plugin", "unsafe"} {
|
||||
if importedPath == forbidden || strings.HasPrefix(importedPath, forbidden+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkCompatibilityGovernance 校验受控动态响应登记、Sunset 版本与运行时遥测保持同步。
|
||||
func checkCompatibilityGovernance(root string) []violation {
|
||||
// matrixPath 是记录外部调用方、删除条件和 Sunset 版本的兼容矩阵路径。
|
||||
matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md")
|
||||
// matrixBytes 是兼容矩阵原文,用于避免受控兼容响应脱离文档治理。
|
||||
matrixBytes, err := os.ReadFile(matrixPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("docs", "architecture", "api-compatibility-matrix.md")), line: 1, message: fmt.Sprintf("无法读取兼容矩阵: %v", err)}}
|
||||
}
|
||||
// matrix 是兼容矩阵文本,统一使用字符串匹配保留文档格式独立性。
|
||||
matrix := string(matrixBytes)
|
||||
// serverPath 是定义历史 API 遥测版本的服务端文件路径。
|
||||
serverPath := filepath.Join(root, "internal", "server", "server.go")
|
||||
// serverBytes 是服务端源码,用于确认每个兼容响应共用实际遥测版本。
|
||||
serverBytes, err := os.ReadFile(serverPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("internal", "server", "server.go")), line: 1, message: fmt.Sprintf("无法读取历史 API 遥测实现: %v", err)}}
|
||||
}
|
||||
// serverSource 是服务端源码文本,供版本与弃用头检查使用。
|
||||
serverSource := string(serverBytes)
|
||||
// violations 保存兼容治理缺失或版本漂移问题。
|
||||
var violations []violation
|
||||
for name /* name 是当前受控动态响应的 Go 类型名。 */, registration /* registration 是该响应的矩阵登记与退场版本。 */ := range controlledDynamicResponses {
|
||||
if !strings.Contains(matrix, "`"+registration.matrixName+"`") && !strings.Contains(matrix, registration.matrixName) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 未登记在兼容矩阵", name)})
|
||||
}
|
||||
if !strings.Contains(matrix, registration.sunsetVersion) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 缺少 Sunset 版本 %s", name, registration.sunsetVersion)})
|
||||
}
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISuccessorLink = "</api/v1>; rel=\"successor-version\"; title=\"v2.0\""`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API successor Link 必须声明与兼容矩阵一致的版本 v2.0"})
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISunsetDate = `) || !strings.Contains(serverSource, `Header().Set("Deprecation", "true")`) || !strings.Contains(serverSource, `Header().Set("Sunset", legacyAPISunsetDate)`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API 必须写入 Deprecation 与 Sunset 遥测头"})
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// isHTTPContractTypeName 判断类型名称是否属于 Server 的 HTTP 响应契约。
|
||||
func isHTTPContractTypeName(name string) bool {
|
||||
// lowerName 统一大小写,兼容 Response、DTO、Envelope 和 Result 的命名习惯。
|
||||
lowerName := strings.ToLower(name)
|
||||
return strings.HasSuffix(lowerName, "response") || strings.HasSuffix(lowerName, "dto") ||
|
||||
strings.HasSuffix(lowerName, "envelope") || strings.HasSuffix(lowerName, "result")
|
||||
}
|
||||
|
||||
// containsDynamicMapType 递归识别以 any/interface{} 为值的动态 map,保留已有键值兼容契约。
|
||||
func containsDynamicMapType(expr ast.Expr) bool {
|
||||
// typedExpr 是当前递归检查的 AST 类型表达式。
|
||||
switch typedExpr := expr.(type) {
|
||||
case *ast.MapType:
|
||||
return isAnyType(typedExpr.Value)
|
||||
case *ast.ArrayType:
|
||||
return containsDynamicMapType(typedExpr.Elt)
|
||||
case *ast.StarExpr:
|
||||
return containsDynamicMapType(typedExpr.X)
|
||||
case *ast.StructType:
|
||||
// field 是当前结构体字段,需继续检查其元素类型。
|
||||
for _, field := range typedExpr.Fields.List {
|
||||
if containsDynamicMapType(field.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAnyType 判断表达式是否为 Go 的 any 或空接口,用于识别无稳定字段边界的响应 map。
|
||||
func isAnyType(expr ast.Expr) bool {
|
||||
// ident 是表达式的标识符形式;ok 表示断言成功。
|
||||
if ident, ok := expr.(*ast.Ident); ok {
|
||||
return ident.Name == "any" || ident.Name == "interface{}"
|
||||
}
|
||||
// interfaceType 是表达式的接口类型形式;ok 表示断言成功。
|
||||
if interfaceType, ok := expr.(*ast.InterfaceType); ok {
|
||||
return interfaceType.Methods != nil && len(interfaceType.Methods.List) == 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isWriteJSONCall 判断调用是否为 Server 的统一 JSON 响应写入函数。
|
||||
func isWriteJSONCall(call *ast.CallExpr) bool {
|
||||
// functionName 是调用目标的简单函数名。
|
||||
functionName, ok := call.Fun.(*ast.Ident)
|
||||
return ok && functionName.Name == "writeJSON"
|
||||
}
|
||||
|
||||
// isDynamicMapLiteral 判断表达式是否直接构造 map 响应,避免匿名契约逃逸静态检查。
|
||||
func isDynamicMapLiteral(expr ast.Expr) bool {
|
||||
// composite 是表达式的复合字面量;ok 表示断言成功。
|
||||
composite, ok := expr.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// isMap 表示复合字面量是否直接构造动态 map。
|
||||
_, isMap := composite.Type.(*ast.MapType)
|
||||
return isMap
|
||||
}
|
||||
|
||||
// checkApplicationTypeLeaks 检查应用 Port 是否泄露数据库、事务或 Server 类型。
|
||||
func checkApplicationTypeLeaks(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if !strings.HasPrefix(filepath.ToSlash(relativePath), "internal/application/") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前应用文件发现的类型泄露。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
switch typedNode /* typedNode 是当前应用声明中的 AST 类型节点。 */ := node.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
// packageName、typeName 保存选择器左侧包名和右侧类型名。
|
||||
packageName, ok := typedNode.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// typeName 是选择器右侧的类型或字段名称。
|
||||
typeName := typedNode.Sel.Name
|
||||
if (packageName.Name == "sql" && typeName == "Tx") || packageName.Name == "db" {
|
||||
violations = append(violations, violation{
|
||||
file: filepath.ToSlash(relativePath), line: fset.Position(typedNode.Pos()).Line,
|
||||
message: fmt.Sprintf("应用 Port 禁止暴露基础设施类型 %s.%s", packageName.Name, typeName),
|
||||
})
|
||||
}
|
||||
case *ast.StarExpr:
|
||||
// ident 是指针类型的目标标识符。
|
||||
ident, ok := typedNode.X.(*ast.Ident)
|
||||
if ok && ident.Name == "Server" {
|
||||
violations = append(violations, violation{
|
||||
file: filepath.ToSlash(relativePath), line: fset.Position(typedNode.Pos()).Line,
|
||||
message: "应用 Port 禁止暴露 *Server 类型",
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// normalizeImportPath 去除当前模块前缀,统一架构规则使用的内部包路径。
|
||||
func normalizeImportPath(importedPath string) string {
|
||||
return strings.TrimPrefix(importedPath, "xianyu-go/")
|
||||
}
|
||||
|
||||
// isForbiddenApplicationImport 判断应用层是否依赖了基础设施或 HTTP 层。
|
||||
func isForbiddenApplicationImport(filePath, importedPath string) bool {
|
||||
if !strings.HasPrefix(filePath, "internal/application/") {
|
||||
return false
|
||||
}
|
||||
for _, forbidden /* forbidden 是应用层禁止依赖的包前缀。 */ := range []string{
|
||||
"internal/db", "internal/server", "internal/xianyu", "internal/browser",
|
||||
"database/sql", "net/http", "github.com/go-chi/chi",
|
||||
} {
|
||||
if importedPath == forbidden || strings.HasPrefix(importedPath, forbidden+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isForbiddenServerLowLevelImport 判断 Server 是否新增了未登记的基础设施依赖。
|
||||
func isForbiddenServerLowLevelImport(filePath, importedPath string) bool {
|
||||
if !strings.HasPrefix(filePath, "internal/server/") || strings.HasSuffix(filePath, "_test.go") {
|
||||
return false
|
||||
}
|
||||
if importedPath != "database/sql" && importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") &&
|
||||
importedPath != "internal/xianyu" && !strings.HasPrefix(importedPath, "internal/xianyu/") &&
|
||||
importedPath != "internal/browser" && !strings.HasPrefix(importedPath, "internal/browser/") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isForbiddenLowLevelImport 判断低层包是否依赖了上层应用包。
|
||||
func isForbiddenLowLevelImport(filePath, importedPath string) bool {
|
||||
// lowLevelPackage 标识当前文件所属的低层包。
|
||||
lowLevelPackage := ""
|
||||
switch {
|
||||
case strings.HasPrefix(filePath, "internal/db/"):
|
||||
lowLevelPackage = "internal/db/"
|
||||
case strings.HasPrefix(filePath, "internal/xianyu/"):
|
||||
lowLevelPackage = "internal/xianyu/"
|
||||
case strings.HasPrefix(filePath, "internal/browser/"):
|
||||
lowLevelPackage = "internal/browser/"
|
||||
}
|
||||
if lowLevelPackage == "" || strings.HasPrefix(importedPath, lowLevelPackage) {
|
||||
return false
|
||||
}
|
||||
// upperPackage 是禁止被低层包依赖的上层包路径。
|
||||
for _, upperPackage := range []string{
|
||||
"internal/server",
|
||||
"internal/adapter",
|
||||
"internal/account",
|
||||
"internal/automation",
|
||||
"internal/engine",
|
||||
"internal/chat",
|
||||
"internal/notify",
|
||||
"internal/auth",
|
||||
} {
|
||||
if importedPath == upperPackage || strings.HasPrefix(importedPath, upperPackage+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// firstLineContaining 返回文本中首次出现目标字符串的行号。
|
||||
func firstLineContaining(source, target string) int {
|
||||
// offset 是目标字符串在原文中的字节偏移。
|
||||
offset := strings.Index(source, target)
|
||||
if offset < 0 {
|
||||
return 0
|
||||
}
|
||||
return 1 + strings.Count(source[:offset], "\n")
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// checkCompatibilityGovernance 校验受控动态响应登记、Sunset 版本与运行时遥测保持同步。
|
||||
func checkCompatibilityGovernance(root string) []violation {
|
||||
// matrixPath 是记录外部调用方、删除条件和 Sunset 版本的兼容矩阵路径。
|
||||
matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md")
|
||||
// matrixBytes 是兼容矩阵原文,用于避免受控兼容响应脱离文档治理。
|
||||
matrixBytes, err := os.ReadFile(matrixPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("docs", "architecture", "api-compatibility-matrix.md")), line: 1, message: fmt.Sprintf("无法读取兼容矩阵: %v", err)}}
|
||||
}
|
||||
// matrix 是兼容矩阵文本,统一使用字符串匹配保留文档格式独立性。
|
||||
matrix := string(matrixBytes)
|
||||
// serverPath 是定义历史 API 遥测版本的服务端文件路径。
|
||||
serverPath := filepath.Join(root, "internal", "server", "server.go")
|
||||
// serverBytes 是服务端源码,用于确认每个兼容响应共用实际遥测版本。
|
||||
serverBytes, err := os.ReadFile(serverPath)
|
||||
if err != nil {
|
||||
return []violation{{file: filepath.ToSlash(filepath.Join("internal", "server", "server.go")), line: 1, message: fmt.Sprintf("无法读取历史 API 遥测实现: %v", err)}}
|
||||
}
|
||||
// serverSource 是服务端源码文本,供版本与弃用头检查使用。
|
||||
serverSource := string(serverBytes)
|
||||
// violations 保存兼容治理缺失或版本漂移问题。
|
||||
var violations []violation
|
||||
for name /* name 是当前受控动态响应的 Go 类型名。 */, registration /* registration 是该响应的矩阵登记与退场版本。 */ := range controlledDynamicResponses {
|
||||
if !strings.Contains(matrix, "`"+registration.matrixName+"`") && !strings.Contains(matrix, registration.matrixName) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 未登记在兼容矩阵", name)})
|
||||
}
|
||||
if !strings.Contains(matrix, registration.sunsetVersion) {
|
||||
violations = append(violations, violation{file: "docs/architecture/api-compatibility-matrix.md", line: 1, message: fmt.Sprintf("动态响应 %s 缺少 Sunset 版本 %s", name, registration.sunsetVersion)})
|
||||
}
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISuccessorLink = "</api/v1>; rel=\"successor-version\"; title=\"v2.0\""`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API successor Link 必须声明与兼容矩阵一致的版本 v2.0"})
|
||||
}
|
||||
if !strings.Contains(serverSource, `legacyAPISunsetDate = `) || !strings.Contains(serverSource, `Header().Set("Deprecation", "true")`) || !strings.Contains(serverSource, `Header().Set("Sunset", legacyAPISunsetDate)`) {
|
||||
violations = append(violations, violation{file: "internal/server/server.go", line: 1, message: "历史 API 必须写入 Deprecation 与 Sunset 遥测头"})
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// isHTTPContractTypeName 判断类型名称是否属于 Server 的 HTTP 响应契约。
|
||||
func isHTTPContractTypeName(name string) bool {
|
||||
// lowerName 统一大小写,兼容 Response、DTO、Envelope 和 Result 的命名习惯。
|
||||
lowerName := strings.ToLower(name)
|
||||
return strings.HasSuffix(lowerName, "response") || strings.HasSuffix(lowerName, "dto") ||
|
||||
strings.HasSuffix(lowerName, "envelope") || strings.HasSuffix(lowerName, "result")
|
||||
}
|
||||
|
||||
// containsDynamicMapType 递归识别以 any/interface{} 为值的动态 map,保留已有键值兼容契约。
|
||||
func containsDynamicMapType(expr ast.Expr) bool {
|
||||
// typedExpr 是当前递归检查的 AST 类型表达式。
|
||||
switch typedExpr := expr.(type) {
|
||||
case *ast.MapType:
|
||||
return isAnyType(typedExpr.Value)
|
||||
case *ast.ArrayType:
|
||||
return containsDynamicMapType(typedExpr.Elt)
|
||||
case *ast.StarExpr:
|
||||
return containsDynamicMapType(typedExpr.X)
|
||||
case *ast.StructType:
|
||||
// field 是当前结构体字段,需继续检查其元素类型。
|
||||
for _, field := range typedExpr.Fields.List {
|
||||
if containsDynamicMapType(field.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isAnyType 判断表达式是否为 Go 的 any 或空接口,用于识别无稳定字段边界的响应 map。
|
||||
func isAnyType(expr ast.Expr) bool {
|
||||
// ident 是表达式的标识符形式;ok 表示断言成功。
|
||||
if ident, ok := expr.(*ast.Ident); ok {
|
||||
return ident.Name == "any" || ident.Name == "interface{}"
|
||||
}
|
||||
// interfaceType 是表达式的接口类型形式;ok 表示断言成功。
|
||||
if interfaceType, ok := expr.(*ast.InterfaceType); ok {
|
||||
return interfaceType.Methods != nil && len(interfaceType.Methods.List) == 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isWriteJSONCall 判断调用是否为 Server 的统一 JSON 响应写入函数。
|
||||
func isWriteJSONCall(call *ast.CallExpr) bool {
|
||||
// functionName 是调用目标的简单函数名。
|
||||
functionName, ok := call.Fun.(*ast.Ident)
|
||||
return ok && functionName.Name == "writeJSON"
|
||||
}
|
||||
|
||||
// isDynamicMapLiteral 判断表达式是否直接构造 map 响应,避免匿名契约逃逸静态检查。
|
||||
func isDynamicMapLiteral(expr ast.Expr) bool {
|
||||
// composite 是表达式的复合字面量;ok 表示断言成功。
|
||||
composite, ok := expr.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
// isMap 表示复合字面量是否直接构造动态 map。
|
||||
_, isMap := composite.Type.(*ast.MapType)
|
||||
return isMap
|
||||
}
|
||||
|
||||
// checkApplicationTypeLeaks 检查应用 Port 是否泄露数据库、事务或 Server 类型。
|
||||
func checkApplicationTypeLeaks(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if !strings.HasPrefix(filepath.ToSlash(relativePath), "internal/application/") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前应用文件发现的类型泄露。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
switch typedNode /* typedNode 是当前应用声明中的 AST 类型节点。 */ := node.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
// packageName、typeName 保存选择器左侧包名和右侧类型名。
|
||||
packageName, ok := typedNode.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// typeName 是选择器右侧的类型或字段名称。
|
||||
typeName := typedNode.Sel.Name
|
||||
if (packageName.Name == "sql" && typeName == "Tx") || packageName.Name == "db" {
|
||||
violations = append(violations, violation{
|
||||
file: filepath.ToSlash(relativePath), line: fset.Position(typedNode.Pos()).Line,
|
||||
message: fmt.Sprintf("应用 Port 禁止暴露基础设施类型 %s.%s", packageName.Name, typeName),
|
||||
})
|
||||
}
|
||||
case *ast.StarExpr:
|
||||
// ident 是指针类型的目标标识符。
|
||||
ident, ok := typedNode.X.(*ast.Ident)
|
||||
if ok && ident.Name == "Server" {
|
||||
violations = append(violations, violation{
|
||||
file: filepath.ToSlash(relativePath), line: fset.Position(typedNode.Pos()).Line,
|
||||
message: "应用 Port 禁止暴露 *Server 类型",
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// normalizeImportPath 去除当前模块前缀,统一架构规则使用的内部包路径。
|
||||
func normalizeImportPath(importedPath string) string {
|
||||
return strings.TrimPrefix(importedPath, "xianyu-go/")
|
||||
}
|
||||
|
||||
// isForbiddenApplicationImport 判断应用层是否依赖了基础设施或 HTTP 层。
|
||||
func isForbiddenApplicationImport(filePath, importedPath string) bool {
|
||||
if !strings.HasPrefix(filePath, "internal/application/") {
|
||||
return false
|
||||
}
|
||||
for _, forbidden /* forbidden 是应用层禁止依赖的包前缀。 */ := range []string{
|
||||
"internal/db", "internal/server", "internal/xianyu", "internal/browser",
|
||||
"database/sql", "net/http", "github.com/go-chi/chi",
|
||||
} {
|
||||
if importedPath == forbidden || strings.HasPrefix(importedPath, forbidden+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isForbiddenServerLowLevelImport 判断 Server 是否新增了未登记的基础设施依赖。
|
||||
func isForbiddenServerLowLevelImport(filePath, importedPath string) bool {
|
||||
if !strings.HasPrefix(filePath, "internal/server/") || strings.HasSuffix(filePath, "_test.go") {
|
||||
return false
|
||||
}
|
||||
if importedPath != "database/sql" && importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") &&
|
||||
importedPath != "internal/xianyu" && !strings.HasPrefix(importedPath, "internal/xianyu/") &&
|
||||
importedPath != "internal/browser" && !strings.HasPrefix(importedPath, "internal/browser/") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isForbiddenLowLevelImport 判断低层包是否依赖了上层应用包。
|
||||
func isForbiddenLowLevelImport(filePath, importedPath string) bool {
|
||||
// lowLevelPackage 标识当前文件所属的低层包。
|
||||
lowLevelPackage := ""
|
||||
switch {
|
||||
case strings.HasPrefix(filePath, "internal/db/"):
|
||||
lowLevelPackage = "internal/db/"
|
||||
case strings.HasPrefix(filePath, "internal/xianyu/"):
|
||||
lowLevelPackage = "internal/xianyu/"
|
||||
case strings.HasPrefix(filePath, "internal/browser/"):
|
||||
lowLevelPackage = "internal/browser/"
|
||||
}
|
||||
if lowLevelPackage == "" || strings.HasPrefix(importedPath, lowLevelPackage) {
|
||||
return false
|
||||
}
|
||||
// upperPackage 是禁止被低层包依赖的上层包路径。
|
||||
for _, upperPackage := range []string{
|
||||
"internal/server",
|
||||
"internal/adapter",
|
||||
"internal/account",
|
||||
"internal/automation",
|
||||
"internal/engine",
|
||||
"internal/chat",
|
||||
"internal/notify",
|
||||
"internal/auth",
|
||||
} {
|
||||
if importedPath == upperPackage || strings.HasPrefix(importedPath, upperPackage+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// firstLineContaining 返回文本中首次出现目标字符串的行号。
|
||||
func firstLineContaining(source, target string) int {
|
||||
// offset 是目标字符串在原文中的字节偏移。
|
||||
offset := strings.Index(source, target)
|
||||
if offset < 0 {
|
||||
return 0
|
||||
}
|
||||
return 1 + strings.Count(source[:offset], "\n")
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// checkStageTwoTransportBoundary 扫描 HTTP transport 与入口包的组合根及平台依赖旁路。
|
||||
func checkStageTwoTransportBoundary(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// isServer 表示当前文件是否属于 HTTP transport 包。
|
||||
isServer := strings.HasPrefix(normalizedPath, "internal/server/")
|
||||
// isServerCommand 表示当前文件是否属于 Server 进程入口包。
|
||||
isServerCommand := strings.HasPrefix(normalizedPath, "cmd/server/")
|
||||
if !isServer && !isServerCommand {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前源码文件违反阶段二边界的全部位置。
|
||||
var violations []violation
|
||||
if isServer && filepath.Base(normalizedPath) == "application_services.go" {
|
||||
violations = append(violations, violation{file: normalizedPath, line: 1, message: "阶段二禁止 internal/server/application_services.go;应用服务、runner 和 coordinator 必须迁入 composition 与应用层"})
|
||||
}
|
||||
// forbiddenImports 是当前阶段不允许出现在 transport 或 cmd 组合入口的跨层依赖。
|
||||
var forbiddenImports map[string]string
|
||||
if isServer {
|
||||
forbiddenImports = map[string]string{
|
||||
"internal/account": "Server 不得直接依赖 account.Manager,必须消费应用 Port",
|
||||
"internal/adapter": "Server 不得直接依赖 adapter 实现或 factory,必须消费应用 Port",
|
||||
"internal/automation": "Server 不得直接依赖 automation.Center,必须消费应用 Port",
|
||||
"internal/browser": "Server 不得直接依赖 browser 实现,必须消费应用 Port",
|
||||
"internal/chat": "Server 不得直接依赖 chat.Service,必须消费聊天应用 Port",
|
||||
"internal/db": "Server 不得直接依赖 db.Store 或 repository,实现必须留在 adapter",
|
||||
"internal/notify": "Server 不得直接依赖 notifier,实现必须留在通知应用 Port",
|
||||
"internal/xianyu": "Server 不得直接依赖平台协议,实现必须留在 adapter",
|
||||
}
|
||||
} else {
|
||||
forbiddenImports = map[string]string{
|
||||
"internal/adapter": "cmd/server 不得直接装配 adapter 服务;必须委托 internal/composition",
|
||||
"internal/account": "cmd/server 不得直接装配账号运行时;必须委托 internal/composition",
|
||||
"internal/automation": "cmd/server 不得直接装配自动化 worker;必须委托 internal/composition",
|
||||
"internal/chat": "cmd/server 不得直接装配聊天服务;必须委托 internal/composition",
|
||||
"internal/notify": "cmd/server 不得直接装配通知 worker;必须委托 internal/composition",
|
||||
"internal/application/": "cmd/server 不得直接构造应用服务或 worker;必须委托 internal/composition",
|
||||
}
|
||||
}
|
||||
// imported 是当前源码声明的内部或标准库导入,必须逐项检查其是否越过当前层边界。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是去除模块前缀后的稳定内部导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
// forbiddenPath 是禁止导入的内部路径前缀;message 是命中后返回给迁移者的具体修复方向。
|
||||
for forbiddenPath, message := range forbiddenImports {
|
||||
if importPath == forbiddenPath || strings.HasPrefix(importPath, forbiddenPath) {
|
||||
violations = append(violations, violation{file: normalizedPath, line: fset.Position(imported.Pos()).Line, message: message})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if isServer {
|
||||
violations = append(violations, checkStageTwoServerDeclarations(normalizedPath, syntax, fset)...)
|
||||
violations = append(violations, checkStageTwoServerConstruction(normalizedPath, syntax, fset)...)
|
||||
violations = append(violations, checkStageTwoApplicationPortDeclarations(normalizedPath, syntax, fset)...)
|
||||
}
|
||||
violations = append(violations, checkStageTwoCompositionProjection(normalizedPath, syntax, fset)...)
|
||||
if isServerCommand {
|
||||
violations = append(violations, checkStageTwoCmdCalls(normalizedPath, syntax, fset)...)
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkStageTwoApplicationPortDeclarations 拒绝 HTTP Port 容器重新持有具体应用服务实现。
|
||||
func checkStageTwoApplicationPortDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if filepath.Base(relativePath) != "application_ports.go" {
|
||||
return nil
|
||||
}
|
||||
// applicationAliases 保存当前文件中应用包的本地导入别名。
|
||||
applicationAliases := applicationImportAliases(syntax)
|
||||
// violations 保存具体应用服务指针泄露到 transport Port 容器的全部位置。
|
||||
var violations []violation
|
||||
// declaration 是当前文件的顶级声明,只有类型声明可能定义 Port 容器。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// generalDeclaration、ok 分别是转换后的通用声明及其类型匹配状态。
|
||||
generalDeclaration, ok := declaration.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是该通用声明中的单个类型规格。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// typeSpecification、ok 分别是转换后的类型规格及其匹配状态。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok || (typeSpecification.Name.Name != "ApplicationPorts" && typeSpecification.Name.Name != "ApplicationPortsInput") {
|
||||
continue
|
||||
}
|
||||
// structure、ok 分别是 Port 容器的结构体定义及其类型匹配状态。
|
||||
structure, ok := typeSpecification.Type.(*ast.StructType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// field 是当前 Port 容器声明的字段,用于检查是否泄露具体应用服务。
|
||||
for _, field := range structure.Fields.List {
|
||||
if !containsConcreteApplicationServicePointer(field.Type, applicationAliases) {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(field.Pos()).Line, message: "阶段二 HTTP 应用 Port 容器不得持有具体 application Service 指针;请在 internal/server 定义消费者接口并由 composition 投影实现"})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// applicationImportAliases 收集 internal/application 子包的本地别名。
|
||||
func applicationImportAliases(syntax *ast.File) map[string]struct{} {
|
||||
// aliases 保存应用包在当前文件中的可见名称。
|
||||
aliases := make(map[string]struct{})
|
||||
// imported 是当前 transport 文件的导入项,用于识别应用包的本地别名。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是标准化后的仓库内导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
if !strings.HasPrefix(importPath, "internal/application/") {
|
||||
continue
|
||||
}
|
||||
// alias 是当前文件使用的应用包本地名称,默认取导入路径末段。
|
||||
alias := filepath.Base(importPath)
|
||||
if imported.Name != nil {
|
||||
alias = imported.Name.Name
|
||||
}
|
||||
if alias != "_" && alias != "." {
|
||||
aliases[alias] = struct{}{}
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
|
||||
// containsConcreteApplicationServicePointer 递归识别字段类型中隐藏的具体应用服务指针。
|
||||
func containsConcreteApplicationServicePointer(expression ast.Expr, applicationAliases map[string]struct{}) bool {
|
||||
// pointer 表示当前类型是否直接持有应用层对象;只有具体 Service/ServiceSet 才违反 Port 边界。
|
||||
if pointer, ok := expression.(*ast.StarExpr); ok {
|
||||
// selector、ok 分别是指针元素的限定类型选择器及其匹配状态。
|
||||
if selector, ok := pointer.X.(*ast.SelectorExpr); ok {
|
||||
// packageName、ok 分别是限定类型所属包标识符及其匹配状态。
|
||||
if packageName, ok := selector.X.(*ast.Ident); ok {
|
||||
// imported 表示该包名是否来自当前文件导入的应用层包。
|
||||
if _, imported := applicationAliases[packageName.Name]; imported && (strings.HasSuffix(selector.Sel.Name, "Service") || strings.HasSuffix(selector.Sel.Name, "ServiceSet")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return containsConcreteApplicationServicePointer(pointer.X, applicationAliases)
|
||||
}
|
||||
// array 表示切片或数组字段;递归避免以集合形式隐藏具体服务。
|
||||
if array, ok := expression.(*ast.ArrayType); ok {
|
||||
return containsConcreteApplicationServicePointer(array.Elt, applicationAliases)
|
||||
}
|
||||
// mapping 表示 map 字段;键和值都不能用于隐藏服务实例。
|
||||
if mapping, ok := expression.(*ast.MapType); ok {
|
||||
return containsConcreteApplicationServicePointer(mapping.Key, applicationAliases) || containsConcreteApplicationServicePointer(mapping.Value, applicationAliases)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkStageTwoCompositionProjection 确保 composition 核心不反向依赖 Server,只有 runtime 子层可以投影 Server 依赖。
|
||||
func checkStageTwoCompositionProjection(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
if !strings.HasPrefix(relativePath, "internal/composition/") || strings.HasPrefix(relativePath, "internal/composition/runtime/") {
|
||||
return nil
|
||||
}
|
||||
// imported 是 composition 核心文件的导入项,核心层不得反向导入 Server。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是导入路径的去引号文本及其解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil || normalizeImportPath(rawPath) != "internal/server" {
|
||||
continue
|
||||
}
|
||||
return []violation{{file: relativePath, line: fset.Position(imported.Pos()).Line, message: "阶段二 composition 核心不得依赖 Server;只能由 internal/composition/runtime 投影 server.Dependencies"}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkStageTwoServerDeclarations 禁止 Server 继续声明服务集合、平台 Port 或反向生命周期 API。
|
||||
func checkStageTwoServerDeclarations(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// forbiddenTypes 是必须从 internal/server 消失的组合根和平台类型。
|
||||
forbiddenTypes := map[string]string{
|
||||
"ApplicationServices": "Server 不能拥有应用服务集合;请迁入 composition 并向 handler 注入最小应用 Port",
|
||||
"ApplicationServiceDependencies": "Server 不能声明应用服务装配依赖;请迁入 composition",
|
||||
"PlatformPort": "Server 不能持有 MTOP、长登录或二维码平台 Port;请迁入对应应用用例",
|
||||
}
|
||||
// forbiddenMethods 是必须从 Server 消失的反向访问器和 session callback。
|
||||
forbiddenMethods := map[string]string{
|
||||
"ApplicationServices": "Server 不得向外返还应用服务集合",
|
||||
"LifecycleComponents": "Server 不得生成或返还应用 worker 生命周期组件",
|
||||
"mtopClient": "Server 不得获取 MTOP 客户端",
|
||||
"longLoginClient": "Server 不得获取长登录客户端",
|
||||
"qrLoginService": "Server 不得获取二维码平台客户端",
|
||||
"sessionRecoveryCallback": "Server 不得创建 session recovery callback",
|
||||
"recoverExpiredMTOPSession": "Server 不得承载 MTOP session 恢复",
|
||||
}
|
||||
// violations 保存声明层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
// declaration 是当前 Server 文件的顶层声明,可能声明禁止的组合根类型或访问器。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// typedDeclaration 是顶层声明的具体语法类型,用于分开处理类型和函数声明。
|
||||
switch typedDeclaration := declaration.(type) {
|
||||
case *ast.GenDecl:
|
||||
if typedDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是当前类型声明块中的单个类型定义。
|
||||
for _, specification := range typedDeclaration.Specs {
|
||||
// typeSpecification、ok 分别是当前语法规格是否为具名类型及其断言结果。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// message、forbidden 分别是命中禁止类型时的修复提示及其匹配结果。
|
||||
if message, forbidden := forbiddenTypes[typeSpecification.Name.Name]; forbidden {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(typeSpecification.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
// message、forbidden 分别是命中禁止 Server 访问器时的修复提示及其匹配结果。
|
||||
if message, forbidden := forbiddenMethods[typedDeclaration.Name.Name]; forbidden {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(typedDeclaration.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkStageTwoServerConstruction 拒绝 Server 直接构造应用服务、runner、coordinator 或 adapter factory。
|
||||
func checkStageTwoServerConstruction(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// internalAliases 保存当前文件中指向 application 或 adapter 的导入别名,供构造调用精确判定。
|
||||
internalAliases := internalConstructionImportAliases(syntax)
|
||||
// violations 保存调用层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数或方法调用。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 表示当前调用的接收者与方法名称。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// name 是当前被调用的方法或构造函数名称。
|
||||
name := selector.Sel.Name
|
||||
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" || name == "sessionRecoveryCallback" || name == "recoverExpiredMTOPSession" || (strings.HasPrefix(name, "New") && isInternalConstructionCall(selector.X, internalAliases)) {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("Server 禁止调用 %s;应用服务、runner、coordinator 和 adapter factory 必须由 composition 构造", name)})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// internalConstructionImportAliases 收集 application 与 adapter 导入的本地别名,避免误判标准库 New 调用。
|
||||
func internalConstructionImportAliases(syntax *ast.File) map[string]struct{} {
|
||||
// aliases 保存需要受阶段二构造门禁保护的本地导入名。
|
||||
aliases := make(map[string]struct{})
|
||||
// imported 是当前待解析别名的导入声明。
|
||||
for _, imported := range syntax.Imports {
|
||||
// rawPath、unquoteErr 分别是当前导入路径及其语法解析错误。
|
||||
rawPath, unquoteErr := strconv.Unquote(imported.Path.Value)
|
||||
if unquoteErr != nil {
|
||||
continue
|
||||
}
|
||||
// importPath 是去除模块前缀后的内部导入路径。
|
||||
importPath := normalizeImportPath(rawPath)
|
||||
if !strings.HasPrefix(importPath, "internal/application/") && !strings.HasPrefix(importPath, "internal/adapter") {
|
||||
continue
|
||||
}
|
||||
// alias 是源码调用选择器使用的包名;显式别名优先于路径末段。
|
||||
alias := filepath.Base(importPath)
|
||||
if imported.Name != nil {
|
||||
alias = imported.Name.Name
|
||||
}
|
||||
if alias != "_" && alias != "." {
|
||||
aliases[alias] = struct{}{}
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
|
||||
// isInternalConstructionCall 判断构造调用是否来自应用/adapter 包或依赖 factory 链。
|
||||
func isInternalConstructionCall(receiver ast.Expr, internalAliases map[string]struct{}) bool {
|
||||
// identifier 是直接包名调用,例如 orderapp.NewRefreshJobRunner。
|
||||
if identifier, ok := receiver.(*ast.Ident); ok {
|
||||
// found 表示该直接接收者是否是 application 或 adapter 的本地导入别名。
|
||||
_, found := internalAliases[identifier.Name]
|
||||
return found
|
||||
}
|
||||
// selector 表示依赖 factory 链,例如 dependencies.ItemDependencies.NewItemBatchRepository。
|
||||
_, isFactoryChain := receiver.(*ast.SelectorExpr)
|
||||
return isFactoryChain
|
||||
}
|
||||
|
||||
// checkStageTwoCmdCalls 拒绝 cmd/server 通过 Server API 或 factory 间接重新承担业务组合根职责。
|
||||
func checkStageTwoCmdCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// violations 保存入口层违反阶段二边界的位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数或方法调用。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 表示当前调用的接收者与名称。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// name 是被调用的构造或生命周期访问器名称。
|
||||
name := selector.Sel.Name
|
||||
if name == "NewApplicationServices" || name == "LifecycleComponents" || name == "ApplicationServices" {
|
||||
violations = append(violations, violation{file: relativePath, line: fset.Position(call.Pos()).Line, message: fmt.Sprintf("cmd/server 禁止通过 %s 使用 Server 组合根;必须调用 internal/composition", name)})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkServerInfrastructureFields 禁止 HTTP Server 保存业务运行时或具体平台实现,避免 transport 成为组合根。
|
||||
func checkServerInfrastructureFields(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// forbiddenTypes 记录 Server 不得作为字段持有者的业务运行时和平台实现类型。
|
||||
forbiddenTypes := map[string]string{
|
||||
"account.Manager": "账号 Manager 必须由进程组合根和应用 Port 持有,Server 只能调用应用服务",
|
||||
"automation.Center": "自动化 Center 必须由应用层持有,Server 不能保存业务 worker",
|
||||
"notify.Notifier": "通知器必须通过通知应用 Port 使用,Server 不能保存基础设施实现",
|
||||
"adapter.PlatformDependencies": "具体平台依赖必须在组合根封装为消费者定义的 Port",
|
||||
"adapter.MTOPClient": "MTOP 客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
"adapter.LongLoginClient": "长登录客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
"adapter.QRLoginService": "二维码客户端必须通过应用 Port 或不可变平台 Port 提供",
|
||||
}
|
||||
// violations 保存 Server 结构体字段违反基础设施持有边界的扫描结果。
|
||||
var violations []violation
|
||||
// declaration 是当前文件中的类型声明,只有 Server 结构体需要本规则检查。
|
||||
for _, declaration := range syntax.Decls {
|
||||
// generalDeclaration 表示可能包含类型定义的声明。
|
||||
generalDeclaration, ok := declaration.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
// specification 是当前声明中的一个类型定义。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// typeSpecification 表示具体类型名及其语法树。
|
||||
typeSpecification, ok := specification.(*ast.TypeSpec)
|
||||
if !ok || typeSpecification.Name.Name != "Server" {
|
||||
continue
|
||||
}
|
||||
// structure 表示 Server 的字段集合;非结构体类型不适用本规则。
|
||||
structure, ok := typeSpecification.Type.(*ast.StructType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// field 是当前待检查的 Server 字段。
|
||||
for _, field := range structure.Fields.List {
|
||||
// typeName 是去掉指针层后的限定类型名;未知表达式保持空字符串。
|
||||
typeName := qualifiedTypeName(field.Type)
|
||||
// message、forbidden 分别表示字段类型的禁止原因及其是否命中。
|
||||
message, forbidden := forbiddenTypes[typeName]
|
||||
if !forbidden {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{file: normalizedPath, line: fset.Position(field.Pos()).Line, message: message})
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
// qualifiedTypeName 返回指针、选择器或标识符类型的稳定文本名,供结构体字段边界规则使用。
|
||||
func qualifiedTypeName(expression ast.Expr) string {
|
||||
// pointer 表示字段是否以指针形式声明;边界规则不区分值与指针持有。
|
||||
if pointer, ok := expression.(*ast.StarExpr); ok {
|
||||
return qualifiedTypeName(pointer.X)
|
||||
}
|
||||
// selector 表示包限定类型,例如 adapter.MTOPClient。
|
||||
if selector, ok := expression.(*ast.SelectorExpr); ok {
|
||||
// packageName、ok 分别表示选择器左侧是否为可解析的包标识符。
|
||||
packageName, ok := selector.X.(*ast.Ident)
|
||||
if ok {
|
||||
return packageName.Name + "." + selector.Sel.Name
|
||||
}
|
||||
}
|
||||
// identifier 表示当前字段是否为未限定类型;本规则当前不禁止未限定类型。
|
||||
if identifier, ok := expression.(*ast.Ident); ok {
|
||||
return identifier.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// checkServerCompositionCalls 禁止已迁出的应用 worker 组合逻辑回流到 Server transport 包。
|
||||
func checkServerCompositionCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// forbiddenConstructors 记录必须由进程组合根创建的应用 worker 构造函数及修复提示。
|
||||
forbiddenConstructors := map[string]string{
|
||||
"NewReconciliationRecoveryCoordinator": "订单补偿恢复协调器必须由 cmd 组合根构造后注入 Server",
|
||||
"NewDatabaseHealth": "数据库健康检查端口必须由 cmd 组合根构造后注入 Server",
|
||||
}
|
||||
// forbiddenMethods 记录 Server 不得再作为应用 worker 生命周期反向提供者的遗留方法。
|
||||
forbiddenMethods := map[string]string{
|
||||
"ApplicationLifecycleComponents": "应用 worker 生命周期组件必须由组合根的应用服务集合登记,Server 不得反向返还组件",
|
||||
}
|
||||
// violations 保存当前 Server 文件中发现的组合根回流问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待检查的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是包函数或对象方法调用;仅包级构造函数可能违反本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// message 是命中构造函数或遗留生命周期方法后返回的组合根迁移提示。
|
||||
message, forbidden := forbiddenConstructors[selector.Sel.Name]
|
||||
if !forbidden {
|
||||
message, forbidden = forbiddenMethods[selector.Sel.Name]
|
||||
}
|
||||
if forbidden {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: message,
|
||||
})
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPRequestContracts 禁止 Server handler 使用匿名请求结构,保证请求契约能够被复用、审计和版本化。
|
||||
func checkHTTPRequestContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") || !strings.HasSuffix(normalizedPath, "_handlers.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 handler 文件中发现的匿名请求结构。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// declaration 是函数体内可能包含请求变量的声明语句。
|
||||
declaration, ok := node.(*ast.DeclStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// generalDeclaration 是具体的 var 声明;短变量声明不会承载匿名 struct 类型。
|
||||
generalDeclaration, ok := declaration.Decl.(*ast.GenDecl)
|
||||
if !ok || generalDeclaration.Tok != token.VAR {
|
||||
return true
|
||||
}
|
||||
// specification 是当前 var 声明中的单个语法规格。
|
||||
for _, specification := range generalDeclaration.Specs {
|
||||
// valueSpecification 是当前 var 声明的名称、类型和初始值组合。
|
||||
valueSpecification, ok := specification.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// anonymousStruct 表示该变量是否直接声明为匿名 struct 类型。
|
||||
_, anonymousStruct := valueSpecification.Type.(*ast.StructType)
|
||||
if !anonymousStruct {
|
||||
continue
|
||||
}
|
||||
// name 是当前匿名结构声明中的变量名。
|
||||
for _, name := range valueSpecification.Names {
|
||||
if name.Name != "req" && name.Name != "input" {
|
||||
continue
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(valueSpecification.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 请求变量 %s 禁止使用匿名 struct,请定义具名 DTO", name.Name),
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkRuntimeSetterCalls 禁止生产代码调用仅为测试替身保留的 Adapter 运行时 setter。
|
||||
func checkRuntimeSetterCalls(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// testOnlySetters 是已登记为测试隔离入口的 Adapter setter 名称。
|
||||
testOnlySetters := map[string]struct{}{
|
||||
"SetAutomation": {}, "SetNotifier": {}, "SetChatService": {}, "SetCredentialWakeService": {},
|
||||
"SetBrowser": {}, "SetRenewService": {}, "SetTokenCaptchaRequester": {}, "SetOrderDetailClient": {},
|
||||
}
|
||||
// violations 保存生产代码绕过构造期依赖固定的调用位置。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// call 是当前待判断的函数调用节点。
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// selector 是当前调用的选择器表达式,只有明确的 Adapter setter 名称才属于本规则。
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// registered 表示当前调用是否属于明确登记的测试兼容 setter。
|
||||
if _, registered := testOnlySetters[selector.Sel.Name]; !registered {
|
||||
return true
|
||||
}
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(call.Pos()).Line,
|
||||
message: fmt.Sprintf("生产代码禁止调用测试兼容 setter %s,请通过构造期 RuntimeBundle 注入", selector.Sel.Name),
|
||||
})
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// checkHTTPResponseContracts 检查 Server 对外响应是否使用具名 DTO,并阻止动态 map 绕过契约边界。
|
||||
func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation {
|
||||
// normalizedPath 是统一使用斜杠的仓库相对路径。
|
||||
normalizedPath := filepath.ToSlash(relativePath)
|
||||
if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
// violations 保存当前 Server 文件发现的 HTTP 契约问题。
|
||||
var violations []violation
|
||||
ast.Inspect(syntax, func(node ast.Node) bool {
|
||||
// typedNode 是当前遍历到的 AST 节点,用于识别 HTTP 契约声明或调用。
|
||||
switch typedNode := node.(type) {
|
||||
case *ast.TypeSpec:
|
||||
if !isHTTPContractTypeName(typedNode.Name.Name) {
|
||||
return true
|
||||
}
|
||||
if (typedNode.Name.Name == "settingsResponse" || containsDynamicMapType(typedNode.Type)) &&
|
||||
!isControlledDynamicResponseType(typedNode.Name.Name) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(typedNode.Pos()).Line,
|
||||
message: fmt.Sprintf("HTTP 契约类型 %s 禁止使用动态 map,请定义具名 DTO 字段", typedNode.Name.Name),
|
||||
})
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if !isWriteJSONCall(typedNode) || len(typedNode.Args) < 3 {
|
||||
return true
|
||||
}
|
||||
// responseArg 是 writeJSON 的响应值参数,必须是具名 DTO 或受控类型。
|
||||
responseArg := typedNode.Args[2]
|
||||
if isDynamicMapLiteral(responseArg) {
|
||||
violations = append(violations, violation{
|
||||
file: normalizedPath,
|
||||
line: fset.Position(responseArg.Pos()).Line,
|
||||
message: "HTTP 响应禁止直接写入动态 map,请使用具名 DTO",
|
||||
})
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免在未满足 Sunset 条件前改变旧客户端 JSON 形状。
|
||||
func isControlledDynamicResponseType(name string) bool {
|
||||
// ok 表示响应类型是否已在带 Sunset 条件的兼容登记表中备案。
|
||||
_, ok := controlledDynamicResponses[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// isForbiddenHiddenDependencyImport 禁止应用与 Server 通过反射、插件机制或动态加载隐藏必需依赖。
|
||||
func isForbiddenHiddenDependencyImport(filePath, importedPath string) bool {
|
||||
// productionLayer 表示必须封死隐式装配旁路的生产层。
|
||||
productionLayer := (strings.HasPrefix(filePath, "internal/application/") && !strings.HasSuffix(filePath, "_test.go")) ||
|
||||
(strings.HasPrefix(filePath, "internal/server/") && !strings.HasSuffix(filePath, "_test.go"))
|
||||
if !productionLayer {
|
||||
return false
|
||||
}
|
||||
for _, forbidden /* forbidden 是禁止隐藏依赖实现的标准库或运行时包名。 */ := range []string{"reflect", "plugin", "unsafe"} {
|
||||
if importedPath == forbidden || strings.HasPrefix(importedPath, forbidden+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in new issue
Block a user