合并 dev 分支全部修复
This commit is contained in:
commit
798e3f3221
32 files changed
+1920
-189
No files matched your search
+12
-3
@@ -160,15 +160,21 @@ func main() {
|
||||
if err := mgr.StartAll(ctx); err != nil {
|
||||
logger.Error("启动账号引擎失败", "err", err)
|
||||
}
|
||||
go automation.NewScheduler(autoCenter).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, ap, logger, notifier).Run(ctx)
|
||||
automationScheduler := automation.NewScheduler(autoCenter)
|
||||
go automationScheduler.Run(ctx)
|
||||
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
|
||||
go renewalScheduler.Run(ctx)
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
go srv.RunPublishBatchRecovery(ctx)
|
||||
srv.StartPublishBatchRecovery(ctx)
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
logger.Error("HTTP 服务退出", "err", err)
|
||||
// 即便出错也尝试清理已启动的账号与浏览器。
|
||||
cancel()
|
||||
srv.WaitForBackground()
|
||||
automationScheduler.Wait()
|
||||
renewalScheduler.Wait()
|
||||
mgr.StopAll()
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
@@ -176,6 +182,9 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
// HTTP 服务正常退出(ctx 取消触发 Shutdown):停账号引擎、关浏览器。
|
||||
srv.WaitForBackground()
|
||||
automationScheduler.Wait()
|
||||
renewalScheduler.Wait()
|
||||
mgr.StopAll()
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
|
||||
+75
-45
@@ -342,6 +342,19 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID string) (*automation.OrderDetail, error) {
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
defer a.orderFetchMu.Unlock()
|
||||
@@ -387,6 +400,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
}
|
||||
if fetchErr != nil {
|
||||
@@ -400,6 +414,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
if 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)
|
||||
}
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
@@ -407,6 +422,15 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.store == nil || a.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
@@ -454,6 +478,7 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
|
||||
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, d)
|
||||
if renewed {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
@@ -467,6 +492,21 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
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)
|
||||
}
|
||||
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
@@ -551,7 +591,7 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
res, err := api.RenewAPIFirst(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
res, err := api.RenewAfterSessionExpired(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
@@ -564,9 +604,40 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingProtocolRenew(d.ID, res)
|
||||
// 官网 Promise 超时只记录错误,不把当前登录态判定为失效。
|
||||
return true, nil
|
||||
// 恢复路径不能把“底层请求仍在进行”提前记为成功,否则上层会
|
||||
// 重置失败计数并继续使用未确认的旧凭证。这里等待最终响应;定时
|
||||
// 调度仍使用异步 watcher,不阻塞健康账号。
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
late, waitErr := res.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
return false, errors.New("协议续期底层响应未返回结果")
|
||||
}
|
||||
var lateSnapshot []cookierefresh.BrowserCookie
|
||||
if late.CookieSnapshotComplete {
|
||||
lateSnapshot = late.CookieSnapshot
|
||||
if lateSnapshot == nil {
|
||||
lateSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if 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 := strings.TrimSpace(late.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
@@ -576,47 +647,6 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (a *Adapter) watchPendingProtocolRenew(cookieID string, result *xrenew.Result) {
|
||||
if result == nil || !result.HasPending() || a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("等待协议续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := xrenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.logger.Info("已异步接收协议续期迟到 Cookie", "account", cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("协议续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
var (
|
||||
_ engine.Handler = (*Adapter)(nil)
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -103,6 +105,27 @@ type fakeOrderDetailClient struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
type scriptedOrderDetailClient struct {
|
||||
mu sync.Mutex
|
||||
results []struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
cookies string
|
||||
}
|
||||
}
|
||||
|
||||
func (f *scriptedOrderDetailClient) FetchOrderDetail(_ context.Context, cookies, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.results) == 0 {
|
||||
return nil, errors.New("unexpected order detail call")
|
||||
}
|
||||
next := f.results[0]
|
||||
f.results = f.results[1:]
|
||||
next.cookies = cookies
|
||||
return next.detail, next.err
|
||||
}
|
||||
|
||||
func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.calls++
|
||||
return f.detail, f.err
|
||||
@@ -380,6 +403,46 @@ func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchOrderDetailSessionExpiredRenewsAndRetries(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
oldCookie := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) + "; havana_lgc2_77=old"
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", oldCookie, `{}`, now.Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{TaskKey: "blocked", CookieID: "cid", TriggerType: automation.TriggerOrderPaid, TaskJSON: `{}`, DueAt: now.Add(time.Hour).Unix(), ErrorMessage: "Session过期"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &scriptedOrderDetailClient{results: []struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
cookies string
|
||||
}{
|
||||
{err: errors.New("token API 返回非成功: FAIL_SYS_SESSION_EXPIRED::Session过期")},
|
||||
{detail: &mtop.OrderDetailResult{Quantity: "1", SpecName: "套餐", SpecValue: "续期版", Amount: "9.9"}},
|
||||
}}
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetOrderDetailClient(client)
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "expired-order", "item", "buyer", "")
|
||||
if err != nil || detail == nil || detail.SpecValue != "续期版" {
|
||||
t.Fatalf("detail=%+v err=%v", detail, err)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("renewed cookie not saved: %q", saved)
|
||||
}
|
||||
var dueAt int64
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='blocked'`).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("credential-blocked task not woken: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
@@ -403,6 +466,45 @@ func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
want bool
|
||||
wantCookie bool
|
||||
}{
|
||||
{name: "late success", body: `{"content":{"data":{"processFinished":true,"resultCode":100}}}`, want: true, wantCookie: true},
|
||||
{name: "late business failure", body: `{"content":{"data":{"processFinished":true,"resultCode":500}}}`, want: false, wantCookie: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "late_cookie", Value: "saved", Path: "/"})
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL,
|
||||
RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond,
|
||||
})
|
||||
if got := a.OnPasswordLoginRefresh(context.Background(), "cid"); got != tt.want {
|
||||
t.Fatalf("pending 最终恢复结果=%v want %v", got, tt.want)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(context.Background(), "cid")
|
||||
if err != nil || strings.Contains(saved, "late_cookie=saved") != tt.wantCookie {
|
||||
t.Fatalf("迟到 Cookie 保存异常: value=%q err=%v", saved, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
|
||||
+131
-19
@@ -19,12 +19,19 @@ import (
|
||||
var (
|
||||
errAutomationDeferred = errors.New("自动化动作已持久化等待执行")
|
||||
errAutomationNeedsReview = errors.New("自动化动作结果需要人工核对")
|
||||
errAutomationQuarantine = errors.New("自动化人工核对状态保存失败")
|
||||
errActionNotPerformed = errors.New("自动化外部动作明确未执行")
|
||||
// ErrMessageNotSent 表示错误发生在调用 WebSocket 发送之前,可以安全重试。
|
||||
// engine 通过 errors.Is 标记“连接尚未就绪”等运行时状态,避免被误判为
|
||||
// 远端可能已经收到消息。
|
||||
ErrMessageNotSent = errors.New("自动化消息确定未发送")
|
||||
)
|
||||
|
||||
type preparationError struct{ err error }
|
||||
|
||||
func (e *preparationError) Error() string { return e.err.Error() }
|
||||
func (e *preparationError) Unwrap() error { return e.err }
|
||||
|
||||
type uncertainActionError struct{ err error }
|
||||
|
||||
func (e *uncertainActionError) Error() string { return e.err.Error() }
|
||||
@@ -66,6 +73,11 @@ type OrderDetailFetcher interface {
|
||||
FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*OrderDetail, error)
|
||||
}
|
||||
|
||||
// CredentialRecoverer 在平台明确返回 Session 失效时执行一次凭证恢复。
|
||||
type CredentialRecoverer interface {
|
||||
RecoverExpiredCredential(ctx context.Context, cookieID string) bool
|
||||
}
|
||||
|
||||
// Notifier 发货结果通知器(多渠道)。可选依赖,未注入时跳过通知。
|
||||
type Notifier interface {
|
||||
NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string)
|
||||
@@ -77,6 +89,7 @@ type Center struct {
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
logger *slog.Logger
|
||||
@@ -98,6 +111,9 @@ func (c *Center) SetMTop(m mtop.Client) { c.mtop = m }
|
||||
// SetOrderDetailFetcher 注入订单详情查询能力。
|
||||
func (c *Center) SetOrderDetailFetcher(fetcher OrderDetailFetcher) {
|
||||
c.fetcher = fetcher
|
||||
if recoverer, ok := fetcher.(CredentialRecoverer); ok {
|
||||
c.recoverer = recoverer
|
||||
}
|
||||
}
|
||||
|
||||
// SetNotifier 注入发货结果通知器。
|
||||
@@ -127,6 +143,13 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
if err := c.markEventFacts(ctx, task); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if task.OrderID != "" {
|
||||
if order, orderErr := c.store.Orders.Get(ctx, task.OrderID); orderErr == nil && order != nil {
|
||||
task = mergeOrderIntoTask(task, order)
|
||||
} else if orderErr != nil && !errors.Is(orderErr, db.ErrNotFound) {
|
||||
return false, fmt.Errorf("读取自动化事件订单事实: %w", orderErr)
|
||||
}
|
||||
}
|
||||
paused, until, err := c.store.Cookies.IsPaused(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -173,6 +196,16 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
var firstErr error
|
||||
for _, rule := range rules {
|
||||
if err := c.executeRule(ctx, task, rule); err != nil {
|
||||
var prepErr *preparationError
|
||||
if errors.As(err, &prepErr) && !isDeferredReplay(task) {
|
||||
dueAt := time.Now().UTC().Add(time.Minute).Unix()
|
||||
if deferErr := c.deferTaskWithError(ctx, task, dueAt, prepErr.Error()); deferErr != nil {
|
||||
return false, errors.Join(err, fmt.Errorf("持久化前置失败任务: %w", deferErr))
|
||||
}
|
||||
c.logger.Warn("自动化前置处理失败,任务已持久化等待恢复", "account", task.AccountID,
|
||||
"order_id", task.OrderID, "trigger", task.TriggerType, "retry_at", dueAt, "err", err)
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, errAutomationDeferred) {
|
||||
return true, nil
|
||||
}
|
||||
@@ -206,7 +239,15 @@ func taskDelayCursor(task Task) int {
|
||||
return cursor
|
||||
}
|
||||
|
||||
func isDeferredReplay(task Task) bool {
|
||||
return task.Raw != nil && task.Raw["automation_deferred_replay"] == true
|
||||
}
|
||||
|
||||
func (c *Center) deferTask(ctx context.Context, task Task, dueAt int64) error {
|
||||
return c.deferTaskWithError(ctx, task, dueAt, "")
|
||||
}
|
||||
|
||||
func (c *Center) deferTaskWithError(ctx context.Context, task Task, dueAt int64, errMsg string) error {
|
||||
key := buildTriggerKey(task)
|
||||
if key == "" {
|
||||
return fmt.Errorf("暂停期间的自动化事件缺少可持久化防重键")
|
||||
@@ -218,7 +259,7 @@ func (c *Center) deferTask(ctx context.Context, task Task, dueAt int64) error {
|
||||
}
|
||||
return c.store.Automation.DeferTask(ctx, db.DeferredAutomationTask{
|
||||
TaskKey: task.AccountID + ":" + key, CookieID: task.AccountID,
|
||||
TriggerType: task.TriggerType, TaskJSON: string(raw), DueAt: dueAt,
|
||||
TriggerType: task.TriggerType, TaskJSON: string(raw), DueAt: dueAt, ErrorMessage: errMsg,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -362,9 +403,12 @@ func immediateManualActions(actions []db.AutomationAction) []db.AutomationAction
|
||||
|
||||
func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationRule) error {
|
||||
var err error
|
||||
if len(task.ActionPlan) == 0 && task.TriggerType != TriggerOrderPaid {
|
||||
task.ActionPlan = runnableActions(task, rule.Actions)
|
||||
}
|
||||
task, err = c.prepareTask(ctx, task)
|
||||
if err != nil {
|
||||
return err
|
||||
return &preparationError{err: err}
|
||||
}
|
||||
triggerKey := buildTriggerKey(task)
|
||||
if triggerKey == "" {
|
||||
@@ -432,15 +476,19 @@ func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationR
|
||||
}
|
||||
if errors.Is(err, errAutomationNeedsReview) {
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
if c.notifier != nil && !errors.Is(err, errAutomationQuarantine) {
|
||||
c.notifyResult(task, "needs_review", sent, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
if sent > 0 {
|
||||
if sent > 0 && !errors.Is(err, ErrMessageNotSent) && !errors.Is(err, errActionNotPerformed) {
|
||||
reason := "运行已完成部分动作,后续动作失败,已禁止从头自动重放: " + err.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
|
||||
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason); quarantineErr != nil {
|
||||
finish = false
|
||||
c.logger.Error("保存自动化人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
|
||||
return errors.Join(errAutomationNeedsReview, errAutomationQuarantine, err, quarantineErr)
|
||||
}
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, "needs_review", sent, reason)
|
||||
@@ -448,12 +496,19 @@ func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationR
|
||||
return fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
|
||||
}
|
||||
status, errMsg = "failed", err.Error()
|
||||
if errors.Is(err, ErrMessageNotSent) || errors.Is(err, errActionNotPerformed) {
|
||||
errMsg = db.SafeRetryErrorPrefix + errMsg
|
||||
}
|
||||
return err
|
||||
}
|
||||
if task.TriggerType == TriggerReviewMissingTimeout && task.OrderID != "" {
|
||||
if incrementErr := c.store.Automation.IncrementReviewRequest(ctx, task.OrderID); incrementErr != nil {
|
||||
reason := "求评价消息已发送,但保存提醒次数失败,已停止自动重放: " + incrementErr.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
|
||||
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason); quarantineErr != nil {
|
||||
finish = false
|
||||
c.logger.Error("保存求评价人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
|
||||
return errors.Join(errAutomationNeedsReview, errAutomationQuarantine, incrementErr, quarantineErr)
|
||||
}
|
||||
finish = false
|
||||
if c.notifier != nil {
|
||||
c.notifyResult(task, "needs_review", sent, reason)
|
||||
@@ -525,14 +580,26 @@ func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64,
|
||||
var uncertain *uncertainActionError
|
||||
if n > 0 || errors.As(actionErr, &uncertain) {
|
||||
reason := "外部动作可能已部分或全部执行,已禁止自动重放,请人工核对: " + actionErr.Error()
|
||||
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent+n, reason)
|
||||
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent+n, reason); quarantineErr != nil {
|
||||
c.logger.Error("保存不确定动作人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
|
||||
return sent + n, false, errors.Join(errAutomationNeedsReview, errAutomationQuarantine, actionErr, quarantineErr)
|
||||
}
|
||||
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, actionErr)
|
||||
}
|
||||
_ = c.store.Automation.AbortRunAction(ctx, run.ID, run.AttemptCount, cursor)
|
||||
if abortErr := c.store.Automation.AbortRunAction(ctx, run.ID, run.AttemptCount, cursor); abortErr != nil {
|
||||
reason := "外部动作明确未执行,但清除动作占用状态失败,已停止自动重放: " + abortErr.Error()
|
||||
if quarantineErr := c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason); quarantineErr != nil {
|
||||
c.logger.Error("隔离动作状态异常的自动化运行失败", "run_id", run.ID, "err", quarantineErr)
|
||||
}
|
||||
return sent, false, fmt.Errorf("%w: %s", errAutomationNeedsReview, reason)
|
||||
}
|
||||
return sent, false, actionErr
|
||||
}
|
||||
if err := c.store.Automation.AdvanceRunAction(ctx, run.ID, run.AttemptCount, cursor, n); err != nil {
|
||||
_ = c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, "动作已执行但检查点保存失败,请人工核对,禁止自动重放: "+err.Error())
|
||||
if quarantineErr := c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, "动作已执行但检查点保存失败,请人工核对,禁止自动重放: "+err.Error()); quarantineErr != nil {
|
||||
c.logger.Error("保存检查点异常的人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
|
||||
return sent + n, false, errors.Join(errAutomationNeedsReview, errAutomationQuarantine, err, quarantineErr)
|
||||
}
|
||||
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
|
||||
}
|
||||
sent += n
|
||||
@@ -627,15 +694,15 @@ func (c *Center) prepareTask(ctx context.Context, task Task) (Task, error) {
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
})
|
||||
needsDetail := task.TriggerType == TriggerOrderPaid || task.TriggerType == TriggerBuyerReviewed
|
||||
needsDetail := task.TriggerType == TriggerOrderPaid
|
||||
if existing, err := c.store.Orders.Get(ctx, task.OrderID); err == nil && existing != nil {
|
||||
task = mergeOrderIntoTask(task, existing)
|
||||
if existing.Quantity == "" || existing.Amount == "" {
|
||||
if needsDetail && (existing.Quantity == "" || existing.Amount == "") {
|
||||
needsDetail = true
|
||||
}
|
||||
// 规则是否多规格由 action.config_json 决定;这里无法提前知道命中的 action,
|
||||
// 因此交易类事件统一补齐规格,确保后续规格映射有事实依据。
|
||||
if existing.SpecName == "" || existing.SpecValue == "" {
|
||||
if needsDetail && (existing.SpecName == "" || existing.SpecValue == "") {
|
||||
needsDetail = true
|
||||
}
|
||||
}
|
||||
@@ -748,6 +815,10 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
if !enabled && !task.ForceConfirmShipment {
|
||||
return nil
|
||||
}
|
||||
return c.confirmShipmentAttempt(ctx, task, true)
|
||||
}
|
||||
|
||||
func (c *Center) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error {
|
||||
credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
@@ -813,6 +884,26 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
sender.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
c.wakeCredentialBlockedAutomation(ctx, task.AccountID)
|
||||
}
|
||||
sessionErr := callErr
|
||||
if sessionErr == nil && !ok {
|
||||
sessionErr = errors.New(strings.Join(ret, "; "))
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(sessionErr) {
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...))
|
||||
}
|
||||
if allowCredentialRecovery && c.recoverer != nil && c.recoverer.RecoverExpiredCredential(ctx, task.AccountID) {
|
||||
c.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return c.confirmShipmentAttempt(ctx, task, false)
|
||||
}
|
||||
if !allowCredentialRecovery {
|
||||
return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
if callErr != nil {
|
||||
if len(persistenceErrs) > 0 {
|
||||
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
|
||||
@@ -846,6 +937,15 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID string) {
|
||||
if c == nil || c.store == nil || c.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := c.store.Automation.WakeCredentialBlocked(ctx, accountID); err != nil {
|
||||
c.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
if !actionMatchesOrderSpec(task, action) {
|
||||
return 0, nil
|
||||
@@ -872,12 +972,12 @@ func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAc
|
||||
}
|
||||
if imageURL != "" {
|
||||
if err := c.sendImage(ctx, task, imageURL, card.ID); err != nil {
|
||||
return sent, uncertainAction(err)
|
||||
return sent, classifyMessageSendError(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
return sent, uncertainAction(err)
|
||||
return sent, classifyMessageSendError(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" {
|
||||
@@ -899,8 +999,13 @@ func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull,
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
// 发送接口报错时无法判断远端是否已经收到。恢复库存会让同一卡密
|
||||
// 再次被消费,因此保守地保留已消费状态并交给人工核对。
|
||||
if errors.Is(err, ErrMessageNotSent) {
|
||||
if restoreErr := c.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil {
|
||||
return sent, uncertainAction(errors.Join(err, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr)))
|
||||
}
|
||||
return sent, err
|
||||
}
|
||||
// 请求已经交给传输层后无法判断远端是否收到,保留消费状态并人工核对。
|
||||
return sent, uncertainAction(err)
|
||||
}
|
||||
}
|
||||
@@ -909,6 +1014,13 @@ func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull,
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func classifyMessageSendError(err error) error {
|
||||
if err == nil || errors.Is(err, ErrMessageNotSent) {
|
||||
return err
|
||||
}
|
||||
return uncertainAction(err)
|
||||
}
|
||||
|
||||
func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) (bool, error) {
|
||||
paused, _, err := c.store.Cookies.IsPaused(ctx, accountID)
|
||||
if err != nil {
|
||||
@@ -1018,14 +1130,14 @@ func (c *Center) sendText(ctx context.Context, task Task, text string) error {
|
||||
|
||||
func (c *Center) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("发送图片缺少 chat_id 或 buyer_id")
|
||||
return fmt.Errorf("%w: 发送图片缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if c.senders == nil {
|
||||
return fmt.Errorf("账号发送器未初始化")
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
sender, ok := c.senders.Sender(task.AccountID)
|
||||
if !ok {
|
||||
return fmt.Errorf("账号未在线,无法发送自动化图片")
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化图片", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
@@ -20,6 +21,15 @@ type fakeMTop struct {
|
||||
consignCalls int
|
||||
consignCookieIn string
|
||||
consignOrderIn string
|
||||
consignCookies []string
|
||||
consignResults []fakeConsignResult
|
||||
}
|
||||
|
||||
type fakeConsignResult struct {
|
||||
ok bool
|
||||
ret []string
|
||||
updated string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeMTop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
|
||||
@@ -29,6 +39,12 @@ func (f *fakeMTop) ConsignContext(_ context.Context, cookiesStr, orderID string)
|
||||
f.consignCalls++
|
||||
f.consignCookieIn = cookiesStr
|
||||
f.consignOrderIn = orderID
|
||||
f.consignCookies = append(f.consignCookies, cookiesStr)
|
||||
if len(f.consignResults) > 0 {
|
||||
result := f.consignResults[0]
|
||||
f.consignResults = f.consignResults[1:]
|
||||
return result.ok, result.ret, result.updated, result.err
|
||||
}
|
||||
return f.consignOk, f.consignRet, f.consignUpdated, f.consignErr
|
||||
}
|
||||
func (f *fakeMTop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
|
||||
@@ -44,6 +60,111 @@ func (f *fakeMTop) RefreshTokenWithDeviceIDContext(context.Context, string, stri
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type fakeCredentialRecoverer struct {
|
||||
store *db.Store
|
||||
calls int
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (f *fakeCredentialRecoverer) FetchOrderDetail(context.Context, string, string, string, string, string) (*OrderDetail, error) {
|
||||
return &OrderDetail{Quantity: "1", Amount: "9.9"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeCredentialRecoverer) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
|
||||
f.calls++
|
||||
if f.fail {
|
||||
return false
|
||||
}
|
||||
detail, err := f.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return f.store.Cookies.UpdateRenewalCookie(ctx, cookieID, "unb=123; _m_h5_tk=fresh_1;", detail.MetadataJSON, time.Now().Unix()) == nil
|
||||
}
|
||||
|
||||
func TestConfirmShipmentRetriesFromCheckpointWithoutResendingCard(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
res, err := store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,text_content,enabled,user_id) VALUES ('gift','text','ONLY-ONCE',1,?)`, admin.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cardID, _ := res.LastInsertId()
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "checkpoint-item", Name: "checkpoint",
|
||||
TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{
|
||||
{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, Enabled: true, SortOrder: 1},
|
||||
{ActionType: ActionConfirmShipment, Enabled: true, SortOrder: 2},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mtopMock := &fakeMTop{consignResults: []fakeConsignResult{
|
||||
{ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}},
|
||||
{ok: true, ret: []string{"SUCCESS::调用成功"}},
|
||||
}}
|
||||
recoverer := &fakeCredentialRecoverer{store: store, fail: true}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(mtopMock)
|
||||
center.SetOrderDetailFetcher(recoverer)
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "checkpoint-order",
|
||||
ItemID: "checkpoint-item", BuyerID: "buyer", ChatID: "chat", Quantity: "1", Amount: "9.9"}
|
||||
if err := center.HandleTask(ctx, task); err == nil {
|
||||
t.Fatal("首次确认发货应因 Session 恢复失败而返回错误")
|
||||
}
|
||||
var status, errMsg string
|
||||
var sent, cursor int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status,error_message,sent_count,action_cursor FROM automation_runs WHERE order_id=?`, task.OrderID).
|
||||
Scan(&status, &errMsg, &sent, &cursor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "failed" || !strings.HasPrefix(errMsg, db.SafeRetryErrorPrefix) || sent != 1 || cursor != 1 {
|
||||
t.Fatalf("status=%q err=%q sent=%d cursor=%d", status, errMsg, sent, cursor)
|
||||
}
|
||||
recoverer.fail = false
|
||||
if _, err := store.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE order_id=?`, task.OrderID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
NewScheduler(center).runRecoveryTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "ONLY-ONCE" {
|
||||
t.Fatalf("恢复确认发货不得重复发送卡密: %v", sender.texts)
|
||||
}
|
||||
if mtopMock.consignCalls != 2 {
|
||||
t.Fatalf("consign calls=%d want 2", mtopMock.consignCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentRecoversExpiredSessionAndRetriesOnlyConsign(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
mtopMock := &fakeMTop{consignResults: []fakeConsignResult{
|
||||
{ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}},
|
||||
{ok: true, ret: []string{"SUCCESS::调用成功"}},
|
||||
}}
|
||||
recoverer := &fakeCredentialRecoverer{store: store}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetMTop(mtopMock)
|
||||
center.SetOrderDetailFetcher(recoverer)
|
||||
if err := center.confirmShipment(ctx, Task{AccountID: "cid", OrderID: "session-order", ItemID: "item", BuyerID: "buyer", ChatID: "chat"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recoverer.calls != 1 || mtopMock.consignCalls != 2 {
|
||||
t.Fatalf("recover calls=%d consign calls=%d want 1/2", recoverer.calls, mtopMock.consignCalls)
|
||||
}
|
||||
if len(mtopMock.consignCookies) != 2 || !strings.Contains(mtopMock.consignCookies[1], "fresh_1") {
|
||||
t.Fatalf("确认发货重试未使用续期 Cookie: %v", mtopMock.consignCookies)
|
||||
}
|
||||
order, err := store.Orders.Get(ctx, "session-order")
|
||||
if err != nil || !order.SystemShipped {
|
||||
t.Fatalf("恢复后应记录系统发货: order=%+v err=%v", order, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterConfirmShipment_MockMTopConsigError 用 mock mtop 验证:
|
||||
// ConsignContext 返回错误时 confirmShipment 透传错误,不写 system_shipped;
|
||||
// ok=false 但无错误时返回"确认发货失败"错误。
|
||||
|
||||
@@ -118,6 +118,136 @@ func TestMessageDefinitelyNotSentIsRetried(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbortRunActionFailureQuarantinesRun(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "abort-failure", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "gift", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.DB.ExecContext(ctx, `CREATE TRIGGER fail_abort_run_action
|
||||
BEFORE UPDATE OF action_started ON automation_runs
|
||||
WHEN OLD.action_started = 1 AND NEW.action_started = 0
|
||||
BEGIN SELECT RAISE(ABORT, 'forced abort failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
center := New(store, testSenderProvider{sender: &testSender{err: fmt.Errorf("%w: websocket unavailable", ErrMessageNotSent)}}, nil)
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "abort-failure-order", ChatID: "chat", BuyerID: "buyer"}
|
||||
if err := center.HandleTask(ctx, task); err == nil || !errors.Is(err, errAutomationNeedsReview) {
|
||||
t.Fatalf("回滚检查点失败后应要求人工核对,err=%v", err)
|
||||
}
|
||||
var status string
|
||||
var actionStarted int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status,action_started FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status, &actionStarted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "needs_review" || actionStarted != 1 {
|
||||
t.Fatalf("status=%q action_started=%d want needs_review/1", status, actionStarted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardDefinitelyNotSentIsRetriedAndDataInventoryRestored(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cardType string
|
||||
cardColumn string
|
||||
}{
|
||||
{name: "text", cardType: "text", cardColumn: "text_content"},
|
||||
{name: "data", cardType: "data", cardColumn: "data_content"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
query := fmt.Sprintf(`INSERT INTO cards (name,type,%s,enabled,user_id) VALUES (?,?,?,?,?)`, tc.cardColumn)
|
||||
res, err := store.DB.ExecContext(ctx, query, "gift", tc.cardType, "GIFT-CODE", 1, admin.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cardID, _ := res.LastInsertId()
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "item-card", Name: "card-retry-" + tc.name,
|
||||
TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{err: fmt.Errorf("%w: websocket reconnecting", ErrMessageNotSent)}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "card-order-" + tc.name,
|
||||
ItemID: "item-card", ChatID: "chat", BuyerID: "buyer"}
|
||||
if err := center.HandleTask(ctx, task); err == nil {
|
||||
t.Fatal("首次卡密发送应返回连接未就绪错误")
|
||||
}
|
||||
var status string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "failed" {
|
||||
t.Fatalf("确定未发送的卡密应进入可重试 failed,got %q", status)
|
||||
}
|
||||
if tc.cardType == "data" {
|
||||
var inventory string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&inventory); err != nil || inventory != "GIFT-CODE" {
|
||||
t.Fatalf("未发送 Data 卡密必须恢复库存: inventory=%q err=%v", inventory, err)
|
||||
}
|
||||
}
|
||||
sender.err = nil
|
||||
if _, err := store.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE order_id=?`, task.OrderID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
NewScheduler(center).runRecoveryTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "GIFT-CODE" {
|
||||
t.Fatalf("连接恢复后应发送一次卡密,got %v", sender.texts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleMatchingUsesStoredOrderItemWhenEventOmitsItemID(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if err := store.Orders.Upsert(ctx, "known-order", db.OrderUpsertOpts{
|
||||
CookieID: "cid", ItemID: "known-item", BuyerID: "buyer", ChatID: "chat",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "known-item", Name: "item-specific-review",
|
||||
TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "review-gift", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
if err := center.HandleTask(ctx, Task{
|
||||
AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "known-order",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "review-gift" {
|
||||
t.Fatalf("应使用本地订单 item_id 匹配商品规则,got %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageCardMissingSenderIsDefinitelyNotSent(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
center := New(store, nil, nil)
|
||||
err := center.sendImage(context.Background(), Task{AccountID: "cid", ChatID: "chat", BuyerID: "buyer"}, "https://example.com/gift.png", 1)
|
||||
if !errors.Is(err, ErrMessageNotSent) {
|
||||
t.Fatalf("图片发送器缺失应标记为明确未发送,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSender) SendImage(context.Context, string, string, string, int64) error { return nil }
|
||||
func (s *testSender) UpdateCookie(cookieStr string) {
|
||||
s.cookieUpdates = append(s.cookieUpdates, cookieStr)
|
||||
@@ -126,10 +256,85 @@ func (s *testSender) UpdateCookie(cookieStr string) {
|
||||
}
|
||||
}
|
||||
|
||||
type testFetcher struct{ detail *OrderDetail }
|
||||
type testFetcher struct {
|
||||
detail *OrderDetail
|
||||
err error
|
||||
calls *int
|
||||
}
|
||||
|
||||
func (f testFetcher) FetchOrderDetail(context.Context, string, string, string, string, string) (*OrderDetail, error) {
|
||||
return f.detail, nil
|
||||
if f.calls != nil {
|
||||
*f.calls++
|
||||
}
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
func TestReviewAutomationsDoNotRequireOrderDetail(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
for _, trigger := range []string{TriggerBuyerReviewed, TriggerReviewMissingTimeout} {
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: trigger, TriggerType: trigger, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: trigger, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
calls := 0
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetOrderDetailFetcher(testFetcher{err: errors.New("must not fetch"), calls: &calls})
|
||||
for i, trigger := range []string{TriggerBuyerReviewed, TriggerReviewMissingTimeout} {
|
||||
task := Task{Source: "ws", AccountID: "cid", TriggerType: trigger, OrderID: fmt.Sprintf("review-no-detail-%d", i), ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"attempt": 1}}
|
||||
if err := center.HandleTask(ctx, task); err != nil {
|
||||
t.Fatalf("%s should not fetch order detail: %v", trigger, err)
|
||||
}
|
||||
}
|
||||
if calls != 0 || len(sender.texts) != 2 {
|
||||
t.Fatalf("order detail calls=%d texts=%v", calls, sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderPaidPreparationFailureIsPersistedAndRecovered(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title,is_multi_spec) VALUES ('cid','pending-item','商品',1)`)
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES (91,'库存','text','RECOVERED-CARD',1,?)`, admin.ID)
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "pending-item", Name: "付款恢复", TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: 91, DeliveryCount: 1, ConfigJSON: `{"spec_name":"套餐","spec_value":"恢复版"}`, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetOrderDetailFetcher(testFetcher{err: errors.New("temporary order API failure")})
|
||||
task := Task{Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "pending-order", ItemID: "pending-item", ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"message_id": "paid-1"}}
|
||||
if err := center.HandleTask(ctx, task); err != nil {
|
||||
t.Fatalf("preparation failure should be durably deferred: %v", err)
|
||||
}
|
||||
var pending, runs int
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_pending_tasks WHERE cookie_id='cid' AND trigger_type='order_paid'`).Scan(&pending)
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_runs WHERE order_id='pending-order'`).Scan(&runs)
|
||||
if pending != 1 || runs != 0 {
|
||||
t.Fatalf("pending=%d runs=%d", pending, runs)
|
||||
}
|
||||
center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "恢复版", Quantity: "1", Amount: "9.9"}})
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`)
|
||||
NewScheduler(center).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "RECOVERED-CARD" {
|
||||
t.Fatalf("recovered sends=%v", sender.texts)
|
||||
}
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_pending_tasks WHERE cookie_id='cid'`).Scan(&pending)
|
||||
var status string
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id='pending-order'`).Scan(&status)
|
||||
if pending != 0 || status != "success" {
|
||||
t.Fatalf("pending=%d status=%q", pending, status)
|
||||
}
|
||||
}
|
||||
|
||||
func newAutomationTestStore(t *testing.T) (*db.Store, func()) {
|
||||
|
||||
@@ -192,9 +192,9 @@ func isBuyerReviewedEvent(f rawFields) bool {
|
||||
// reminderContent=[我完成了评价]
|
||||
// updateKey=chat_id:order_id:10:BUYER_RATE_SELLER:26
|
||||
// 仅“服务评价邀请”不含 BUYER_RATE_SELLER,不能误触发赠品。
|
||||
return strings.Contains(f.redReminder, "有新交易评价") &&
|
||||
strings.Contains(f.text, "我完成了评价") &&
|
||||
strings.Contains(f.updateKey, "BUYER_RATE_SELLER")
|
||||
// BUYER_RATE_SELLER 是交易评价的稳定业务标识。展示文案会因客户端版本、
|
||||
// 同一买家重复购买等场景变化,不能再把两段中文文案同时存在作为必要条件。
|
||||
return strings.Contains(strings.ToUpper(f.updateKey), "BUYER_RATE_SELLER")
|
||||
}
|
||||
|
||||
func extFields(ext string) (updateKey, contentType string) {
|
||||
|
||||
@@ -29,6 +29,21 @@ func TestExtractTaskFromWS_BuyerReviewed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTaskFromWS_BuyerReviewedUsesBusinessKeyAcrossCopyVariants(t *testing.T) {
|
||||
raw := mustMap(t, `{
|
||||
"1":{"2":"62904549781@goofish","10":{
|
||||
"reminderContent":"感谢您的再次购买,评价已经完成",
|
||||
"senderUserId":"buyer-2",
|
||||
"reminderUrl":"fleamarket://message_chat?itemId=item-2&peerUserId=buyer-2&sid=62904549781",
|
||||
"extJson":"{\"updateKey\":\"62904549781:order-second:10:buyer_rate_seller:26\",\"contentType\":\"26\"}"
|
||||
}}
|
||||
}`)
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task == nil || task.TriggerType != TriggerBuyerReviewed || task.OrderID != "order-second" {
|
||||
t.Fatalf("second-purchase review task=%+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTaskFromWS_ServiceReviewInvitationIgnored(t *testing.T) {
|
||||
raw := mustMap(t, `{
|
||||
"1": {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -18,11 +19,13 @@ const defaultReviewRequestScanInterval = time.Minute
|
||||
type Scheduler struct {
|
||||
center *Center
|
||||
interval time.Duration
|
||||
runOnce sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewScheduler 构造计划任务调度器。
|
||||
func NewScheduler(center *Center) *Scheduler {
|
||||
return &Scheduler{center: center, interval: defaultReviewRequestScanInterval}
|
||||
return &Scheduler{center: center, interval: defaultReviewRequestScanInterval, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Run 周期扫描计划任务。调用方应在 goroutine 中启动,并用 ctx 控制生命周期。
|
||||
@@ -30,16 +33,28 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
if s == nil || s.center == nil || s.center.store == nil {
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(s.interval)
|
||||
defer ticker.Stop()
|
||||
s.scan(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
s.runOnce.Do(func() {
|
||||
defer close(s.done)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.scan(ctx)
|
||||
}
|
||||
ticker := time.NewTicker(s.interval)
|
||||
defer ticker.Stop()
|
||||
s.scan(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.scan(ctx)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) Wait() {
|
||||
if s != nil && s.done != nil {
|
||||
<-s.done
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,20 +141,31 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
}
|
||||
allowed, err := s.center.accountAutomationAllowed(ctx, task.AccountID)
|
||||
if err != nil || !allowed {
|
||||
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
continue
|
||||
}
|
||||
if !s.center.accountSenderReady(task.AccountID) {
|
||||
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(defaultReviewRequestScanInterval).Unix())
|
||||
if postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(10*time.Minute).Unix()); postponeErr != nil {
|
||||
s.center.logger.Warn("延期自动化恢复任务失败", "run_id", run.ID, "err", postponeErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
rule, err := s.center.store.Automation.Get(ctx, run.RuleID)
|
||||
if err != nil || !rule.Enabled {
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
s.center.logger.Warn("读取自动化恢复规则失败,保留任务等待重试", "run_id", run.ID, "rule_id", run.RuleID, "err", err)
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, db.ErrNotFound) || rule == nil || !rule.Enabled {
|
||||
reason := "自动化规则不存在或已停用,无法恢复"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
continue
|
||||
}
|
||||
if recoveryNeedsSender(task, *rule, run.ActionCursor) && !s.center.accountSenderReady(task.AccountID) {
|
||||
if postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(defaultReviewRequestScanInterval).Unix()); postponeErr != nil {
|
||||
s.center.logger.Warn("等待 WebSocket 时延期自动化任务失败", "run_id", run.ID, "err", postponeErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
claimed, claimErr := s.center.store.Automation.ClaimRecoveryRun(ctx, run.ID, time.Now().UTC().Add(5*time.Minute).Unix())
|
||||
if claimErr != nil || !claimed {
|
||||
continue
|
||||
@@ -155,6 +181,22 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func recoveryNeedsSender(task Task, rule db.AutomationRule, cursor int) bool {
|
||||
actions := task.ActionPlan
|
||||
if len(actions) == 0 {
|
||||
actions = runnableActions(task, rule.Actions)
|
||||
}
|
||||
if cursor < 0 || cursor >= len(actions) {
|
||||
return false
|
||||
}
|
||||
switch actions[cursor].ActionType {
|
||||
case ActionSendText, ActionSendCard:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
tasks, err := s.center.store.Automation.ClaimDueDeferredTasks(ctx, 100)
|
||||
if err != nil {
|
||||
@@ -167,6 +209,10 @@ func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
_ = s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, false, "解析任务失败: "+err.Error())
|
||||
continue
|
||||
}
|
||||
if task.Raw == nil {
|
||||
task.Raw = map[string]any{}
|
||||
}
|
||||
task.Raw["automation_deferred_replay"] = true
|
||||
deferredAgain, runErr := s.center.handleTask(ctx, task)
|
||||
if deferredAgain {
|
||||
// handleTask 已按新的 paused_until 重置同一任务;当前 claim 不再删除。
|
||||
|
||||
@@ -299,3 +299,36 @@ func TestSchedulerScansMoreThanOneReviewPage(t *testing.T) {
|
||||
t.Fatalf("sent=%d want 205", len(sender.texts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryNeedsSenderUsesNextActionType(t *testing.T) {
|
||||
rule := db.AutomationRule{Actions: []db.AutomationAction{
|
||||
{ActionType: ActionConfirmShipment, Enabled: true},
|
||||
{ActionType: ActionSendText, Enabled: true},
|
||||
}}
|
||||
task := Task{TriggerType: TriggerBuyerReviewed}
|
||||
if recoveryNeedsSender(task, rule, 0) {
|
||||
t.Fatal("确认发货动作不应等待 WebSocket")
|
||||
}
|
||||
if !recoveryNeedsSender(task, rule, 1) {
|
||||
t.Fatal("发送文本动作必须等待 WebSocket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationSchedulerWaitsForShutdown(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
scheduler := NewScheduler(New(store, testSenderProvider{sender: &testSender{}}, nil))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
scheduler.Run(ctx)
|
||||
close(done)
|
||||
}()
|
||||
cancel()
|
||||
scheduler.Wait()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("自动化调度器关闭后没有退出")
|
||||
}
|
||||
}
|
||||
+61
-13
@@ -12,6 +12,9 @@ import (
|
||||
|
||||
var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行")
|
||||
|
||||
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
|
||||
const SafeRetryErrorPrefix = "[safe_retry]"
|
||||
|
||||
// AutomationRules 管理自动化规则、动作和执行记录。
|
||||
//
|
||||
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
|
||||
@@ -89,6 +92,7 @@ type DeferredAutomationTask struct {
|
||||
TaskJSON string
|
||||
DueAt int64
|
||||
ClaimVersion int
|
||||
ErrorMessage string
|
||||
}
|
||||
|
||||
var ErrDeferredTaskLeaseLost = errors.New("延迟自动化任务租约已失效")
|
||||
@@ -441,7 +445,8 @@ func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerK
|
||||
attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE rule_id=? AND trigger_key=?
|
||||
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`,
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`,
|
||||
leaseExpiresAt, ruleID, triggerKey, now, now)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
@@ -535,20 +540,25 @@ func (a *AutomationRules) QuarantineRunResult(ctx context.Context, runID int64,
|
||||
}
|
||||
|
||||
// PostponeRecoveryRun 把暂时不能执行的账号移到恢复队列尾部,避免固定的前 100 条饿死后续任务。
|
||||
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID, retryAt int64) error {
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID int64, attempt int, retryAt int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET lease_expires_at=CASE WHEN status='running' THEN ? ELSE lease_expires_at END,
|
||||
next_retry_at=CASE WHEN status='failed' THEN ? ELSE next_retry_at END,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('running','failed')`, retryAt, retryAt, runID)
|
||||
return err
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND attempt_count=? AND action_started=0 AND status IN ('running','failed')`, retryAt, retryAt, runID, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return requireAutomationRunOwner(res)
|
||||
}
|
||||
|
||||
func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpiresAt int64) (bool, error) {
|
||||
now := time.Now().UTC().Unix()
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`, leaseExpiresAt, runID, now, now)
|
||||
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -559,7 +569,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
|
||||
// FinishRun 标记执行完成或失败。
|
||||
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
|
||||
nextRetryAt := int64(0)
|
||||
if status == "failed" && sentCount == 0 {
|
||||
if status == "failed" && (sentCount == 0 || strings.HasPrefix(errMsg, SafeRetryErrorPrefix)) {
|
||||
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
|
||||
}
|
||||
res, err := a.DB.ExecContext(ctx, `
|
||||
@@ -595,7 +605,8 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
|
||||
status,sent_count,error_message,raw_event_json,lease_expires_at,attempt_count,next_retry_at,action_cursor,action_started
|
||||
FROM automation_runs
|
||||
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?)
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%'))
|
||||
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -638,7 +649,7 @@ func (a *AutomationRules) RecoverDefinitelyUnsentReviewRuns(ctx context.Context)
|
||||
func (a *AutomationRules) DeferTask(ctx context.Context, task DeferredAutomationTask) error {
|
||||
_, 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{
|
||||
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",
|
||||
@@ -646,8 +657,8 @@ VALUES (?,?,?,?,?,'pending',0,0,'')`+dialectUpsert(a.Dialect, []string{"task_key
|
||||
"status": "'pending'",
|
||||
"attempt_count": "0",
|
||||
"lease_expires_at": "0",
|
||||
"error_message": "''",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt)
|
||||
"error_message": "excluded.error_message",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt, task.ErrorMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -846,13 +857,50 @@ func (a *AutomationRules) FinishDeferredTask(ctx context.Context, id int64, clai
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
retryDelay := deferredRetryDelay(claimVersion)
|
||||
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(time.Minute).Unix(), errMsg, id, claimVersion)
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(retryDelay).Unix(), errMsg, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
func deferredRetryDelay(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
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 := 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 := 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
|
||||
}
|
||||
|
||||
func (a *AutomationRules) RenewDeferredTaskLease(ctx context.Context, id int64, claimVersion int, leaseExpiresAt int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
|
||||
@@ -504,6 +504,37 @@ func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostponeRecoveryRunCannotOverwriteNewOwnerLease(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
uid, cid := seedAccount(t, s)
|
||||
ruleID, _ := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "item", "paid", true, 0))
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid, TriggerType: "paid", TriggerKey: "postpone-fence"})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start run: id=%d started=%v err=%v", runID, started, err)
|
||||
}
|
||||
stale, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newLease := time.Now().UTC().Add(5 * time.Minute).Unix()
|
||||
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, newLease)
|
||||
if err != nil || !claimed {
|
||||
t.Fatalf("claim=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := s.Automation.PostponeRecoveryRun(ctx, runID, stale.AttemptCount, time.Now().UTC().Add(time.Minute).Unix()); !errors.Is(err, ErrAutomationRunLeaseLost) {
|
||||
t.Fatalf("stale postpone err=%v want lease lost", err)
|
||||
}
|
||||
current, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil || current.LeaseExpiresAt != newLease {
|
||||
t.Fatalf("new owner lease was overwritten: run=%+v err=%v", current, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidJSON validJSON 的非法 JSON 兜底为 {}。
|
||||
func TestValidJSON(t *testing.T) {
|
||||
if got := validJSON(""); got != "{}" {
|
||||
@@ -562,7 +593,7 @@ func TestAutomationIssuesCanBeListedAndResolved(t *testing.T) {
|
||||
if run.Status != "running" || run.ActionStarted || run.ActionCursor != 1 {
|
||||
t.Fatalf("resolved run=%+v", run)
|
||||
}
|
||||
if err := s.Automation.PostponeRecoveryRun(ctx, runID, 4102444800); err != nil {
|
||||
if err := s.Automation.PostponeRecoveryRun(ctx, runID, run.AttemptCount, 4102444800); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
|
||||
@@ -655,6 +686,55 @@ func TestDeferTaskRevivesDeadLetterWithFreshAttemptBudget(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredRetryBackoffAndCredentialWake(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "wake-task", CookieID: cid, TriggerType: "order_paid", TaskJSON: `{}`, DueAt: 0, ErrorMessage: "FAIL_SYS_SESSION_EXPIRED"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim=%v err=%v", claimed, err)
|
||||
}
|
||||
before := time.Now().UTC().Unix()
|
||||
if err := s.Automation.FinishDeferredTask(ctx, claimed[0].ID, claimed[0].ClaimVersion, false, "session expired"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var dueAt int64
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE id=?`, claimed[0].ID).Scan(&dueAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dueAt < before+int64((5*time.Minute)/time.Second)-1 {
|
||||
t.Fatalf("first retry due_at=%d before=%d", dueAt, before)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "ws-wake", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: before + 3600, ErrorMessage: "当前没有可用 WebSocket 连接"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='ws-wake'`).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("WS 恢复必须立即唤醒任务: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE id=?`, claimed[0].ID).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("wake due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "intentional-delay", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: before + 3600}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='intentional-delay'`).Scan(&dueAt); err != nil || dueAt != before+3600 {
|
||||
t.Fatalf("intentional delay must not be woken: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredTaskFencingRejectsStaleWorker(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -577,6 +577,136 @@ func TestMultiDB_AutomationTryStartRunDedup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_DeferredAutomationCredentialWake 验证延迟任务的失败退避和凭证恢复唤醒
|
||||
// 在各数据库方言下行为一致,同时确保正常的业务延迟不会被提前唤醒。
|
||||
func TestMultiDB_DeferredAutomationCredentialWake(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
suffix := fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
username := tg.name + "_deferred_user_" + suffix
|
||||
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create user: ok=%v err=%v", ok, err)
|
||||
}
|
||||
user, _ := s.Users.GetByUsername(ctx, username)
|
||||
cookieID := tg.name + "_deferred_cookie_" + suffix
|
||||
if err := s.Cookies.Save(ctx, cookieID, "cv", user.ID); err != nil {
|
||||
t.Fatalf("save cookie: %v", err)
|
||||
}
|
||||
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{
|
||||
TaskKey: "credential-" + suffix, CookieID: cookieID, TriggerType: "order_paid",
|
||||
TaskJSON: `{}`, DueAt: 0, ErrorMessage: "FAIL_SYS_SESSION_EXPIRED",
|
||||
}); err != nil {
|
||||
t.Fatalf("defer credential task: %v", err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim credential task: tasks=%+v err=%v", claimed, err)
|
||||
}
|
||||
before := time.Now().UTC().Unix()
|
||||
if err := s.Automation.FinishDeferredTask(ctx, claimed[0].ID, claimed[0].ClaimVersion, false, "session expired"); err != nil {
|
||||
t.Fatalf("finish failed task: %v", err)
|
||||
}
|
||||
|
||||
intentionalDue := before + 3600
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{
|
||||
TaskKey: "intentional-" + suffix, CookieID: cookieID, TriggerType: "buyer_reviewed",
|
||||
TaskJSON: `{}`, DueAt: intentionalDue,
|
||||
}); err != nil {
|
||||
t.Fatalf("defer intentional task: %v", err)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
t.Fatalf("wake credential tasks: %v", err)
|
||||
}
|
||||
|
||||
var credentialDue, normalDue int64
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key=?`, "credential-"+suffix).Scan(&credentialDue); err != nil {
|
||||
t.Fatalf("read credential due_at: %v", err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key=?`, "intentional-"+suffix).Scan(&normalDue); err != nil {
|
||||
t.Fatalf("read intentional due_at: %v", err)
|
||||
}
|
||||
if credentialDue != 0 {
|
||||
t.Fatalf("credential task due_at=%d want 0", credentialDue)
|
||||
}
|
||||
if normalDue != intentionalDue {
|
||||
t.Fatalf("intentional task due_at=%d want %d", normalDue, intentionalDue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiDB_AutomationSafeCheckpointRetry(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
suffix := fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
username := tg.name + "_checkpoint_user_" + suffix
|
||||
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create user: ok=%v err=%v", ok, err)
|
||||
}
|
||||
user, _ := s.Users.GetByUsername(ctx, username)
|
||||
cookieID := tg.name + "_checkpoint_cookie_" + suffix
|
||||
if err := s.Cookies.Save(ctx, cookieID, "cv", user.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ruleID, err := s.Automation.Create(ctx, AutomationRuleInput{
|
||||
UserID: user.ID, CookieID: cookieID, Name: "checkpoint", TriggerType: "order_paid", Enabled: true,
|
||||
Actions: []AutomationActionInput{{ActionType: "send_text", Enabled: true}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
|
||||
RuleID: ruleID, CookieID: cookieID, OrderID: "order-" + suffix,
|
||||
TriggerType: "order_paid", TriggerKey: "order_paid:order-" + suffix, RawEventJSON: `{}`,
|
||||
})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("start run: started=%v err=%v", started, err)
|
||||
}
|
||||
if ok, err := s.Automation.StartRunAction(ctx, runID, 1, 0, time.Now().Add(time.Minute).Unix()); err != nil || !ok {
|
||||
t.Fatalf("start first action: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if err := s.Automation.AdvanceRunAction(ctx, runID, 1, 0, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := s.Automation.StartRunAction(ctx, runID, 1, 1, time.Now().Add(time.Minute).Unix()); err != nil || !ok {
|
||||
t.Fatalf("start second action: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if err := s.Automation.AbortRunAction(ctx, runID, 1, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.FinishRun(ctx, runID, 1, "failed", 1, SafeRetryErrorPrefix+"session expired"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
|
||||
if err != nil || len(due) != 1 || due[0].ID != runID || due[0].ActionCursor != 1 || due[0].SentCount != 1 {
|
||||
t.Fatalf("due=%+v err=%v", due, err)
|
||||
}
|
||||
newLease := time.Now().Add(5 * time.Minute).Unix()
|
||||
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, newLease)
|
||||
if err != nil || !claimed {
|
||||
t.Fatalf("claim safe checkpoint: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := s.Automation.PostponeRecoveryRun(ctx, runID, due[0].AttemptCount, time.Now().Add(time.Minute).Unix()); !errors.Is(err, ErrAutomationRunLeaseLost) {
|
||||
t.Fatalf("stale postpone err=%v want lease lost", err)
|
||||
}
|
||||
current, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil || current.LeaseExpiresAt != newLease {
|
||||
t.Fatalf("claimed lease overwritten: run=%+v err=%v", current, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_Notifications 验证通知渠道创建 + 账号绑定读写。
|
||||
func TestMultiDB_Notifications(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
|
||||
+211
-29
@@ -86,6 +86,14 @@ type accountEventHandler interface {
|
||||
OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string)
|
||||
}
|
||||
|
||||
type credentialUpdateHandler interface {
|
||||
OnCredentialUpdated(ctx context.Context, cookieID string)
|
||||
}
|
||||
|
||||
type transportReadyHandler interface {
|
||||
OnTransportReady(ctx context.Context, cookieID string)
|
||||
}
|
||||
|
||||
type tokenCaptchaHandler interface {
|
||||
OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL, deviceID string) (*mtop.RefreshResult, bool)
|
||||
}
|
||||
@@ -118,11 +126,16 @@ type ChatMessage struct {
|
||||
|
||||
// RuntimeStatus 是账号引擎的实时连接状态,不写入数据库。
|
||||
type RuntimeStatus struct {
|
||||
State string `json:"state"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Connected bool `json:"connected"`
|
||||
Failures int `json:"failures"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
State string `json:"state"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Connected bool `json:"connected"`
|
||||
Failures int `json:"failures"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
TokenAcquiredAt time.Time `json:"token_acquired_at,omitempty"`
|
||||
TokenExpiresAt time.Time `json:"token_expires_at,omitempty"`
|
||||
TokenRefreshAt time.Time `json:"token_refresh_at,omitempty"`
|
||||
TokenRemainingSeconds int64 `json:"token_remaining_seconds,omitempty"`
|
||||
TokenRefreshStatus string `json:"token_refresh_status,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -176,6 +189,9 @@ type Account struct {
|
||||
tokenFetchFailures int
|
||||
credentialFP string // 当前内存扁平 Cookie + 权威 Jar 的完整状态指纹
|
||||
tokenCredentialFP string // currentToken 获取完成时绑定的完整凭证状态
|
||||
tokenAcquiredAt time.Time
|
||||
tokenExpiresAt time.Time
|
||||
tokenRefreshAt time.Time
|
||||
|
||||
// 去重
|
||||
dedupMu sync.Mutex
|
||||
@@ -197,8 +213,10 @@ type Account struct {
|
||||
|
||||
reply *ReplyService
|
||||
|
||||
wsRecordOnce sync.Once
|
||||
wsRecordQueue chan db.WSMessage
|
||||
wsRecordOnce sync.Once
|
||||
wsRecordWG sync.WaitGroup
|
||||
wsRecordQueue chan db.WSMessage
|
||||
pendingRenewWG sync.WaitGroup
|
||||
}
|
||||
|
||||
type debounceEntry struct {
|
||||
@@ -316,7 +334,11 @@ func New(cfg Config) *Account {
|
||||
// 调用方应在独立 goroutine 中运行;Stop 可优雅停止。
|
||||
func (a *Account) Run(parent context.Context) error {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
cancel()
|
||||
a.wsRecordWG.Wait()
|
||||
a.pendingRenewWG.Wait()
|
||||
}()
|
||||
a.mu.Lock()
|
||||
a.stopFn = cancel
|
||||
a.mu.Unlock()
|
||||
@@ -324,11 +346,11 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.runtimeCtx = ctx
|
||||
a.accepting = true
|
||||
a.taskMu.Unlock()
|
||||
a.startWSRecorder(ctx)
|
||||
if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
|
||||
a.logger.Info("账号在启动续期前已禁用")
|
||||
return nil
|
||||
}
|
||||
a.startWSRecorder(ctx)
|
||||
// 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建
|
||||
// FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时
|
||||
// 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS;
|
||||
@@ -403,12 +425,14 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
return err
|
||||
}
|
||||
// authTokenCallback 的任意 reject 都被官方 loginV2 映射为
|
||||
// CONN_ERROR=5,页面不会自动 reConnect。
|
||||
reason := "获取消息凭证失败,请重新登录"
|
||||
a.setRuntimeState(RuntimeAuthExpired, reason)
|
||||
a.notifyOffline(ctx, reason+":"+errString(err))
|
||||
return err
|
||||
// 网络或服务端瞬时错误不能让账号运行时永久退出。只要登录 Session
|
||||
// 没有明确失效,就持续重试获取连接级 Token。
|
||||
a.setRuntimeState(RuntimeReconnecting, "获取消息凭证失败,正在重试")
|
||||
a.notifyOffline(ctx, "获取消息凭证失败,正在自动重试:"+errString(err))
|
||||
if sleepErr := sleepCtx(ctx, a.tokenRetryDelay()); sleepErr != nil {
|
||||
return sleepErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.currentToken = token
|
||||
@@ -459,12 +483,14 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.lastOfflineReason = ""
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
a.notifyTransportReady(ctx)
|
||||
if shouldRecovered {
|
||||
a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线",
|
||||
fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince)))
|
||||
}
|
||||
|
||||
// 3) 健康连接只维持心跳和收包;token 只在下一次注册前更新。
|
||||
// 3) 健康连接维持心跳和收包,并在服务端 Token 过期前主动关闭,
|
||||
// 进入下一轮连接以重新调用 Token API 和 /reg。
|
||||
hbCtx, hbCancel := context.WithCancel(ctx)
|
||||
var hbErr error
|
||||
hbDone := make(chan struct{})
|
||||
@@ -474,9 +500,38 @@ func (a *Account) Run(parent context.Context) error {
|
||||
hbCancel()
|
||||
close(hbDone)
|
||||
}()
|
||||
rotateCh := make(chan struct{}, 1)
|
||||
a.mu.Lock()
|
||||
refreshAt := a.tokenRefreshAt
|
||||
expiresAt := a.tokenExpiresAt
|
||||
a.mu.Unlock()
|
||||
if refreshAt.IsZero() || !refreshAt.After(time.Now()) {
|
||||
refreshAt = time.Now()
|
||||
}
|
||||
rotateTimer := time.NewTimer(time.Until(refreshAt))
|
||||
rotateDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(rotateDone)
|
||||
select {
|
||||
case <-hbCtx.Done():
|
||||
case <-rotateTimer.C:
|
||||
select {
|
||||
case rotateCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
recvErr := conn.ReceiveLoop(ctx, a.dispatch)
|
||||
if !rotateTimer.Stop() {
|
||||
select {
|
||||
case <-rotateTimer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
hbCancel()
|
||||
<-rotateDone
|
||||
<-hbDone // 确保 hbErr 写入完成后再读取(消除数据竞争)。
|
||||
_ = conn.Close()
|
||||
if ctx.Err() != nil {
|
||||
@@ -490,6 +545,14 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.conn = nil
|
||||
a.mu.Unlock()
|
||||
connectedDuration := time.Since(startedAt)
|
||||
select {
|
||||
case <-rotateCh:
|
||||
a.logger.Info("WS Token 到达提前轮换时间,正在重新获取 Token", "expires_at", expiresAt, "remaining", time.Until(expiresAt).Round(time.Second))
|
||||
a.clearConnectionToken(ctx)
|
||||
a.setRuntimeState(RuntimeReconnecting, "WS Token 即将到期,正在主动轮换")
|
||||
continue
|
||||
default:
|
||||
}
|
||||
if ws.IsConnectLimitError(recvErr) {
|
||||
a.clearConnectionToken(ctx)
|
||||
reason := "消息会话已被服务端移除"
|
||||
@@ -562,7 +625,9 @@ func (a *Account) startWSRecorder(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
a.wsRecordOnce.Do(func() {
|
||||
a.wsRecordWG.Add(1)
|
||||
go func() {
|
||||
defer a.wsRecordWG.Done()
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(ctx, WSRecordWriteTimeout)
|
||||
deleted, cleanupErr := a.store.WSMessages.DeleteBefore(cleanupCtx, a.CookieID, time.Now().Add(-WSRecordRetention))
|
||||
cleanupCancel()
|
||||
@@ -695,6 +760,18 @@ func (a *Account) beginTask() (context.Context, bool) {
|
||||
|
||||
// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
|
||||
func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
// 先执行低成本登录态检查。它可能仅凭 loginuser.get 响应头恢复签名
|
||||
// Cookie,也能在进入静默续期前准确识别风控状态。
|
||||
loginStatus := a.tryLoginStatusCheck(ctx)
|
||||
if loginStatus.riskRequired {
|
||||
return fmt.Errorf("账号 %s 需要完成安全验证", a.CookieID)
|
||||
}
|
||||
if loginStatus.recovered {
|
||||
a.logger.Info("登录态检查已恢复 Cookie,重置失败计数")
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
|
||||
a.resetFailures()
|
||||
return sleepCtx(ctx, 2*time.Second)
|
||||
}
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
@@ -800,10 +877,55 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
if !ok {
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
}
|
||||
defer credentialUnlock()
|
||||
a.mu.Lock()
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
res, err := checker.CheckLoginStatusContext(ctx, cookieStr)
|
||||
requestCtx := ctx
|
||||
var cookieSession *mtop.CookieSession
|
||||
metadataJSON := ""
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if detailErr != nil || detail == nil {
|
||||
if detailErr == nil {
|
||||
detailErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("登录态检查前读取最新 Cookie 失败", "err", detailErr)
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
cookieStr = detail.Value
|
||||
metadataJSON = detail.MetadataJSON
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
}
|
||||
res, err := checker.CheckLoginStatusContext(requestCtx, cookieStr)
|
||||
if cookieSession != nil {
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
if changed {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadataJSON, snapshot)
|
||||
}
|
||||
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, value, metadata, time.Now().Unix()); persistErr != nil {
|
||||
a.logger.Warn("登录态检查保存响应 Cookie Jar 失败", "err", persistErr)
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
a.replaceCredentialState(value, credentialStateFingerprint(value, metadata))
|
||||
a.clearTokenCache(ctx)
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
if err != nil {
|
||||
a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err)
|
||||
}
|
||||
return loginStatusCheckResult{recovered: res != nil && res.Status == mtop.LoginStatusTokenRefreshed}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("登录态检查失败", "err", err)
|
||||
return loginStatusCheckResult{}
|
||||
@@ -816,7 +938,7 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
a.logger.Warn("登录态检查命中风控验证", "ret", strings.Join(res.Ret, ","), "verification_url", res.VerificationURL)
|
||||
return loginStatusCheckResult{riskRequired: true, verificationURL: res.VerificationURL}
|
||||
}
|
||||
if a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
|
||||
if res.Status == mtop.LoginStatusTokenRefreshed && len(cookierefresh.ChangedCookieNames(cookieStr, res.UpdatedCookies)) > 0 && a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
|
||||
a.logger.Info("登录态检查刷新了 Cookie", "status", res.Status, "message", res.Message)
|
||||
return loginStatusCheckResult{recovered: true}
|
||||
}
|
||||
@@ -877,7 +999,7 @@ func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Contex
|
||||
return false, err
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingAPIRenew(res)
|
||||
a.watchPendingAPIRenew(ctx, res)
|
||||
}
|
||||
updated := false
|
||||
persisted := false
|
||||
@@ -914,6 +1036,9 @@ func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Contex
|
||||
} else {
|
||||
updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
|
||||
}
|
||||
if updated && persisted {
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("接口续期失败,已保存响应 Cookie", "err", err)
|
||||
@@ -951,12 +1076,14 @@ func (a *Account) persistRenewFlatCookie(ctx context.Context, newCookies string)
|
||||
return a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix())
|
||||
}
|
||||
|
||||
func (a *Account) watchPendingAPIRenew(result *renew.Result) {
|
||||
func (a *Account) watchPendingAPIRenew(parent context.Context, result *renew.Result) {
|
||||
if result == nil || !result.HasPending() {
|
||||
return
|
||||
}
|
||||
a.pendingRenewWG.Add(1)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer a.pendingRenewWG.Done()
|
||||
ctx, cancel := context.WithTimeout(parent, 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
@@ -999,6 +1126,7 @@ func (a *Account) persistPendingRenewCookies(ctx context.Context, result *renew.
|
||||
}
|
||||
a.replaceCredentialState(newCookies, credentialStateFingerprint(newCookies, metadata))
|
||||
a.clearTokenCache(ctx)
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
a.logger.Info("已异步接收官网静默续期迟到 Cookie", "updated", strings.Join(result.UpdatedCookieNames, ","))
|
||||
return nil
|
||||
}
|
||||
@@ -1026,9 +1154,16 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, source+"已更新登录凭证,正在重新连接")
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Account) notifyCredentialUpdated(ctx context.Context) {
|
||||
if handler, ok := a.handler.(credentialUpdateHandler); ok {
|
||||
handler.OnCredentialUpdated(ctx, a.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// retryDelay 按错误类型计算退避,并加入 0-30% 抖动。
|
||||
// 多账号同时断线时,纯固定退避会让所有账号在同一秒重连,容易形成重连风暴。
|
||||
func (a *Account) retryDelay(errMsg string) time.Duration {
|
||||
@@ -1287,6 +1422,7 @@ func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr strin
|
||||
return cookieStr, err
|
||||
}
|
||||
a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata))
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
return res.UpdatedCookies, nil
|
||||
}
|
||||
if res.UpdatedCookies != cookieStr {
|
||||
@@ -1398,12 +1534,25 @@ func tokenFailureIsNonCounted(status string) bool {
|
||||
// It is diagnostic state only: acquireToken never reads the accessToken back
|
||||
// for a later WebSocket registration.
|
||||
func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) {
|
||||
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
|
||||
if accessToken == "" {
|
||||
return
|
||||
}
|
||||
expireAt := effectiveTokenExpireAt(serverExpireAt, time.Now())
|
||||
now := time.Now()
|
||||
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
|
||||
a.mu.Lock()
|
||||
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))
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
expireAt := effectiveTokenExpireAt(serverExpireAt, now)
|
||||
if expireAt == 0 {
|
||||
a.logger.Warn("token API 未返回可用过期时间,本次 token 不持久化")
|
||||
// 服务端未给有效期时仍使用保守运行时轮换时间,但不把推测期限
|
||||
// 伪装成服务端缓存期限。
|
||||
a.logger.Warn("token API 未返回可用过期时间,使用保守轮换时间", "refresh_at", refreshAt)
|
||||
a.clearTokenCache(ctx)
|
||||
return
|
||||
}
|
||||
@@ -1506,12 +1655,45 @@ func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string
|
||||
func (a *Account) RuntimeStatus() RuntimeStatus {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
remaining := int64(0)
|
||||
if !a.tokenExpiresAt.IsZero() {
|
||||
remaining = int64(time.Until(a.tokenExpiresAt).Seconds())
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
}
|
||||
return RuntimeStatus{
|
||||
State: a.runtimeState,
|
||||
Message: a.runtimeMessage,
|
||||
Connected: a.conn != nil && a.runtimeState == RuntimeOnline,
|
||||
Failures: a.connFailures,
|
||||
UpdatedAt: a.runtimeUpdatedAt,
|
||||
State: a.runtimeState,
|
||||
Message: a.runtimeMessage,
|
||||
Connected: a.conn != nil && a.runtimeState == RuntimeOnline,
|
||||
Failures: a.connFailures,
|
||||
UpdatedAt: a.runtimeUpdatedAt,
|
||||
TokenAcquiredAt: a.tokenAcquiredAt,
|
||||
TokenExpiresAt: a.tokenExpiresAt,
|
||||
TokenRefreshAt: a.tokenRefreshAt,
|
||||
TokenRemainingSeconds: remaining,
|
||||
TokenRefreshStatus: a.lastTokenStatus,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Account) tokenRetryDelay() time.Duration {
|
||||
a.mu.Lock()
|
||||
expiresAt := a.tokenExpiresAt
|
||||
failures := a.tokenFetchFailures
|
||||
a.mu.Unlock()
|
||||
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
|
||||
}
|
||||
|
||||
func (a *Account) notifyTransportReady(ctx context.Context) {
|
||||
if handler, ok := a.handler.(transportReadyHandler); ok {
|
||||
handler.OnTransportReady(ctx, a.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -401,6 +401,36 @@ func TestTryAPIRenewPersistsLatePromiseCookieWithoutRestart(t *testing.T) {
|
||||
t.Fatal("迟到的 silentHasLogin Set-Cookie 未写回账号")
|
||||
}
|
||||
|
||||
func TestTryAPIRenewPendingWatcherStopsWithAccountContext(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
initial := "unb=123; havana_lgc_exp=" + fmt.Sprint(time.Now().Add(time.Hour).UnixMilli())
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acc.replaceCookieStr(initial)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: fmt.Sprint(time.Now().Add(time.Hour).UnixMilli()), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
acc.renewer = xrenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
if acc.tryAPIRenew(ctx) {
|
||||
t.Fatal("Promise 超时不得伪装成同步续期成功")
|
||||
}
|
||||
cancel()
|
||||
acc.pendingRenewWG.Wait()
|
||||
detail, err := store.Cookies.GetDetails(context.Background(), "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(detail.Value, "sdkSilent=") || strings.Contains(acc.currentCookieStr(), "sdkSilent=") {
|
||||
t.Fatalf("账号关闭后不应接纳迟到 Cookie: db=%q runtime=%q", detail.Value, acc.currentCookieStr())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
|
||||
// 及告警去重逻辑(仅从非验证态进入验证态时告警一次)。
|
||||
func TestSetRuntimeError_AllBranches(t *testing.T) {
|
||||
|
||||
@@ -60,6 +60,9 @@ func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, fu
|
||||
Store: store,
|
||||
Handler: h,
|
||||
})
|
||||
// 通用账号测试默认不启用 loginuser.get;需要验证登录态恢复的用例会
|
||||
// 显式注入 statusMtop,避免单元测试访问真实网络。
|
||||
acc.mtop = &fakeRunMtop{token: "test-token"}
|
||||
return acc, h, store, func() { d.Close() }
|
||||
}
|
||||
|
||||
|
||||
@@ -264,6 +264,37 @@ func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T) {
|
||||
newCookie := "unb=123; _m_h5_tk=loginuser_recovered; sgcookie=abc"
|
||||
mtopClient := &statusMtop{
|
||||
fakeRunMtop: fakeRunMtop{token: "tok-1"},
|
||||
result: &mtop.LoginStatusResult{
|
||||
Status: mtop.LoginStatusTokenRefreshed,
|
||||
UpdatedCookies: newCookie,
|
||||
Message: "令牌已刷新",
|
||||
},
|
||||
}
|
||||
acc, handler, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
acc.mu.Lock()
|
||||
acc.connFailures = MaxConnectionFailures
|
||||
acc.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := acc.handleMaxFailures(ctx); err != ctx.Err() {
|
||||
t.Fatalf("登录态恢复后的等待应响应上下文取消: %v", err)
|
||||
}
|
||||
if handler.refresh != 0 {
|
||||
t.Fatalf("loginuser.get 已恢复时不应继续协议续期,calls=%d", handler.refresh)
|
||||
}
|
||||
if got := acc.currentCookieStr(); got != newCookie {
|
||||
t.Fatalf("登录态检查恢复 Cookie=%q want %q", got, newCookie)
|
||||
}
|
||||
if acc.connFailures != 0 {
|
||||
t.Fatalf("登录态恢复后失败计数=%d want 0", acc.connFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache DB cookie 变更时采纳新 cookie 并清旧 token 缓存。
|
||||
func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
|
||||
+70
-11
@@ -23,6 +23,16 @@ type fakeRunMtop struct{ token string }
|
||||
func (f *fakeRunMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type shortTokenMtop struct {
|
||||
fakeRunMtop
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *shortTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
|
||||
call := s.calls.Add(1)
|
||||
return &mtop.RefreshResult{AccessToken: fmt.Sprintf("short-%d", call), AccessTokenExpireAt: time.Now().Add(2 * time.Second).Unix()}, nil
|
||||
}
|
||||
func (f *fakeRunMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
|
||||
return true, nil, "", nil
|
||||
}
|
||||
@@ -90,6 +100,8 @@ type fakeWSConn struct {
|
||||
sentTexts []string
|
||||
sentImages []string
|
||||
heartbeatDone chan struct{}
|
||||
closeCh chan struct{}
|
||||
closeOnce sync.Once
|
||||
// onReceive 在 ReceiveLoop 启动时被调用,参数是 onMessage 回调,便于测试投递消息。
|
||||
onReceive func(onMessage func(map[string]any))
|
||||
// recvBlock 控制 ReceiveLoop 是否阻塞到 ctx 取消(默认 true)。
|
||||
@@ -119,6 +131,14 @@ func (f *fakeWSConn) ReceiveLoop(ctx context.Context, onMessage func(map[string]
|
||||
f.onReceive(onMessage)
|
||||
}
|
||||
if f.recvBlock {
|
||||
if f.closeCh != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-f.closeCh:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
@@ -129,9 +149,42 @@ func (f *fakeWSConn) Close() error {
|
||||
f.mu.Lock()
|
||||
f.closed = true
|
||||
f.mu.Unlock()
|
||||
if f.closeCh != nil {
|
||||
f.closeOnce.Do(func() { close(f.closeCh) })
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRunRotatesTokenBeforeExpiry(t *testing.T) {
|
||||
tokenClient := &shortTokenMtop{}
|
||||
acc, _, _, cleanup := newRunAccount(t, tokenClient)
|
||||
defer cleanup()
|
||||
first := &fakeWSConn{recvBlock: true, closeCh: make(chan struct{})}
|
||||
second := &fakeWSConn{recvBlock: true, closeCh: make(chan struct{})}
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
deadline := time.Now().Add(4 * time.Second)
|
||||
for tokenClient.calls.Load() < 2 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if got := tokenClient.calls.Load(); got < 2 {
|
||||
cancel()
|
||||
t.Fatalf("Token 到期前未主动轮换,calls=%d status=%+v", got, acc.RuntimeStatus())
|
||||
}
|
||||
status := acc.RuntimeStatus()
|
||||
if status.TokenExpiresAt.IsZero() || status.TokenRefreshAt.IsZero() || !status.TokenRefreshAt.Before(status.TokenExpiresAt) {
|
||||
t.Fatalf("Token 有效期状态异常: %+v", status)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("账号在 Token 轮换测试后未退出")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error {
|
||||
f.mu.Lock()
|
||||
f.sentTexts = append(f.sentTexts, text)
|
||||
@@ -619,7 +672,7 @@ func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
|
||||
func TestRun_TokenFetchFailureRetriesWithoutDisablingAccount(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
|
||||
defer cleanup()
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
|
||||
@@ -629,15 +682,15 @@ func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
|
||||
acc.tokenFetchFailures = TokenFetchDisableThreshold - 1
|
||||
acc.mu.Unlock()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(context.Background()) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, errFakeDial) {
|
||||
t.Fatalf("token callback reject should enter CONN_ERROR, got %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Run did not stop after token callback reject")
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for acc.RuntimeStatus().State != RuntimeReconnecting && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if status := acc.RuntimeStatus(); status.State != RuntimeReconnecting {
|
||||
t.Fatalf("runtime state=%q want %q", status.State, RuntimeReconnecting)
|
||||
}
|
||||
if !store.Cookies.GetStatus(context.Background(), "cid") {
|
||||
t.Fatal("token failure threshold must not disable account")
|
||||
@@ -647,8 +700,14 @@ func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
|
||||
t.Fatalf("unexpected disable event: events=%+v alerts=%+v", h.events, h.alerts)
|
||||
}
|
||||
}
|
||||
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
|
||||
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run error=%v want context canceled", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Run did not stop after cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ import (
|
||||
|
||||
const tokenExpirySafetyMargin = time.Minute
|
||||
|
||||
const (
|
||||
tokenFallbackLifetime = 30 * time.Minute
|
||||
tokenRefreshLeadTime = 10 * time.Minute
|
||||
)
|
||||
|
||||
func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
|
||||
ttl := time.Unix(serverExpireAt, 0).Sub(now)
|
||||
if ttl <= 0 {
|
||||
@@ -24,6 +29,23 @@ func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
|
||||
return now.Add(ttl - margin).Unix()
|
||||
}
|
||||
|
||||
func tokenRotationSchedule(serverExpireAt int64, now time.Time) (expiresAt, refreshAt time.Time) {
|
||||
expiresAt = time.Unix(serverExpireAt, 0)
|
||||
if serverExpireAt <= now.Unix() {
|
||||
expiresAt = now.Add(tokenFallbackLifetime)
|
||||
}
|
||||
ttl := expiresAt.Sub(now)
|
||||
lead := ttl / 10
|
||||
if lead < tokenRefreshLeadTime {
|
||||
lead = tokenRefreshLeadTime
|
||||
}
|
||||
if lead >= ttl {
|
||||
lead = ttl / 2
|
||||
}
|
||||
refreshAt = expiresAt.Add(-lead)
|
||||
return expiresAt, refreshAt
|
||||
}
|
||||
|
||||
func credentialCookieFingerprint(cookieStr string) string {
|
||||
var canonical strings.Builder
|
||||
for _, part := range strings.Split(cookieStr, ";") {
|
||||
|
||||
@@ -25,6 +25,22 @@ func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenRotationScheduleStartsBeforeServerExpiry(t *testing.T) {
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
expiresAt, refreshAt := tokenRotationSchedule(now.Add(time.Hour).Unix(), now)
|
||||
if !refreshAt.Before(expiresAt) || refreshAt != expiresAt.Add(-tokenRefreshLeadTime) {
|
||||
t.Fatalf("refresh_at=%s expires_at=%s", refreshAt, expiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenRotationScheduleUsesFallbackWhenExpiryMissing(t *testing.T) {
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
expiresAt, refreshAt := tokenRotationSchedule(0, now)
|
||||
if expiresAt != now.Add(tokenFallbackLifetime) || !refreshAt.Before(expiresAt) || !refreshAt.After(now) {
|
||||
t.Fatalf("fallback refresh_at=%s expires_at=%s", refreshAt, expiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(t *testing.T) {
|
||||
left := credentialCookieFingerprint("unb=1; cookie2=abc; _m_h5_tk=tk_1")
|
||||
right := credentialCookieFingerprint("_m_h5_tk=tk_1; unb=1; cookie2=abc")
|
||||
|
||||
+174
-28
@@ -9,6 +9,7 @@ import (
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -57,6 +58,10 @@ type Scheduler struct {
|
||||
api apirenew.Service
|
||||
cooldown *CooldownManager
|
||||
notifier RenewalNotifier
|
||||
runOnce sync.Once
|
||||
done chan struct{}
|
||||
workers sync.WaitGroup
|
||||
watchers sync.WaitGroup
|
||||
}
|
||||
|
||||
type RenewalNotifier interface {
|
||||
@@ -81,6 +86,7 @@ func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRef
|
||||
api: apirenew.Service{},
|
||||
cooldown: GlobalCooldown,
|
||||
notifier: notifier,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,13 +94,54 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
if s == nil || s.store == nil {
|
||||
return
|
||||
}
|
||||
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
// 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼
|
||||
// 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。
|
||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||
// 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
|
||||
// 协议;Chromium 不参与普通 Cookie 续期。
|
||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
|
||||
s.runOnce.Do(func() {
|
||||
go func() {
|
||||
defer close(s.done)
|
||||
s.workers.Add(2)
|
||||
go func() {
|
||||
defer s.workers.Done()
|
||||
s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
}()
|
||||
// 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼
|
||||
// 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。
|
||||
// cookies_refresh 仅作为旧配置名的兼容别名。两套配置必须汇聚到同一个
|
||||
// goroutine,否则同时开启时会重复续期并连续重启同一账号。
|
||||
go func() {
|
||||
defer s.workers.Done()
|
||||
s.runAPICookieRenewFixed(ctx)
|
||||
}()
|
||||
s.workers.Wait()
|
||||
s.watchers.Wait()
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
// Wait 等待定时循环和迟到响应 watcher 完成。
|
||||
func (s *Scheduler) Wait() {
|
||||
if s == nil || s.done == nil {
|
||||
return
|
||||
}
|
||||
<-s.done
|
||||
}
|
||||
|
||||
func (s *Scheduler) runAPICookieRenewFixed(ctx context.Context) {
|
||||
if s.apiRenewEnabled(ctx) {
|
||||
s.executeAPICookieRenew(ctx)
|
||||
}
|
||||
for {
|
||||
timer := time.NewTimer(s.apiRenewInterval(ctx))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if !s.apiRenewEnabled(ctx) {
|
||||
continue
|
||||
}
|
||||
s.logger.Info("执行续期任务", "task", "api_cookie_renew")
|
||||
s.executeAPICookieRenew(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey string, defaultEnabled bool, defaultInterval time.Duration, fn func(context.Context)) {
|
||||
@@ -140,7 +187,14 @@ func (s *Scheduler) executeLoginRenew(ctx context.Context) {
|
||||
|
||||
func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
defer credentialUnlock()
|
||||
credentialUpdated := false
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if credentialUpdated {
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
s.restartAfterCredentialUpdate(ctx, account.ID, account.Enabled, "登录态续期")
|
||||
}
|
||||
}()
|
||||
started := time.Now()
|
||||
latest, err := s.reloadRenewalAccount(ctx, account)
|
||||
if err != nil {
|
||||
@@ -184,6 +238,7 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
s.logger.Warn("login_renew 保存响应 Cookie Jar 失败", "account", account.ID, "err", persistErr)
|
||||
return
|
||||
}
|
||||
credentialUpdated = true
|
||||
}
|
||||
if callErr != nil {
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", callErr.Error(), updated, time.Since(started))
|
||||
@@ -205,6 +260,7 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
|
||||
return
|
||||
}
|
||||
credentialUpdated = true
|
||||
}
|
||||
}
|
||||
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated, time.Since(started))
|
||||
@@ -232,10 +288,19 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
|
||||
func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
credentialLocked := true
|
||||
credentialChanged := false
|
||||
credentialPersisted := false
|
||||
restartHandled := false
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
if credentialPersisted {
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
if !restartHandled {
|
||||
s.restartAfterCredentialUpdate(ctx, account.ID, account.Enabled, "接口续期响应 Cookie")
|
||||
}
|
||||
}
|
||||
}()
|
||||
started := time.Now()
|
||||
latest, err := s.reloadRenewalAccount(ctx, account)
|
||||
@@ -259,7 +324,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
return
|
||||
}
|
||||
if res.HasPending() {
|
||||
s.watchPendingAPIRenew(account.ID, res)
|
||||
s.watchPendingAPIRenew(ctx, batchID, account.ID, res)
|
||||
}
|
||||
stepDetails := make([]string, 0, len(res.StepDetails)+1)
|
||||
for _, step := range res.StepDetails {
|
||||
@@ -272,11 +337,15 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
if res.CookieSnapshotComplete {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, res.CookieSnapshot)
|
||||
}
|
||||
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
|
||||
// 扁平 Cookie 的排序和尾分号不是凭证变化;只有字段值变化才需要
|
||||
// 写回和重启。完整 Jar 则还要比较 Domain/Path/Expires 等 metadata。
|
||||
credentialChanged = len(updated) > 0 || metadata != account.MetadataJSON
|
||||
if credentialChanged && !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
|
||||
s.logger.Warn("接口续期任务失败", "account", account.ID, "method", res.RenewMethod, "err", "保存 Cookie 失败")
|
||||
return
|
||||
}
|
||||
credentialPersisted = credentialChanged
|
||||
}
|
||||
if callErr != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{
|
||||
@@ -287,11 +356,12 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
s.logger.Warn("接口续期任务失败,已保存响应头 Cookie", "account", account.ID, "method", res.RenewMethod, "updated", strings.Join(updated, ","), "err", callErr)
|
||||
return
|
||||
}
|
||||
if res.Success && account.Enabled {
|
||||
if res.Success && account.Enabled && credentialChanged {
|
||||
s.logger.Info("接口续期任务成功", "account", account.ID, "method", res.RenewMethod, "updated", strings.Join(updated, ","), "message", res.Message)
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if restarter, ok := s.starter.(accountRestarter); ok {
|
||||
restartHandled = true
|
||||
s.logger.Info("接口续期成功,正在重启账号以应用最新登录凭证", "account", account.ID)
|
||||
if err := restarter.Restart(ctx, account.ID); err != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
|
||||
@@ -332,76 +402,152 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) restartAfterCredentialUpdate(ctx context.Context, accountID string, enabled bool, source string) {
|
||||
if !enabled || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
restarter, ok := s.starter.(accountRestarter)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.logger.Info("认证 Cookie 已更新,正在重启账号以刷新 WS Token", "account", accountID, "source", source)
|
||||
if err := restarter.Restart(ctx, accountID); err != nil {
|
||||
s.logger.Warn("认证 Cookie 已更新,但重启账号刷新 WS Token 失败", "account", accountID, "source", source, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*apirenew.Result, error) {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
|
||||
}
|
||||
|
||||
func (s *Scheduler) watchPendingAPIRenew(cookieID string, result *apirenew.Result) {
|
||||
func (s *Scheduler) watchPendingAPIRenew(ctx context.Context, batchID, cookieID string, result *apirenew.Result) {
|
||||
if result == nil || !result.HasPending() || s.store == nil || s.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
s.watchers.Add(1)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
defer s.watchers.Done()
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
late, waitErr := result.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("等待定时静默续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: "failed", ErrorMessage: waitErr.Error(), RenewMethod: "auto_login_plugin"})
|
||||
}
|
||||
return
|
||||
}
|
||||
opCtx, opCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer opCancel()
|
||||
var finalErr error
|
||||
changed := func() bool {
|
||||
unlock := s.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := s.store.Cookies.GetDetails(ctx, cookieID)
|
||||
detail, getErr := s.store.Cookies.GetDetails(opCtx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
finalErr = getErr
|
||||
return false
|
||||
}
|
||||
newCookies, metadata, changed := apirenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(opCtx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
finalErr = saveErr
|
||||
return false
|
||||
}
|
||||
if s.store.Tokens != nil {
|
||||
_ = s.store.Tokens.Clear(ctx, cookieID)
|
||||
_ = s.store.Tokens.Clear(opCtx, cookieID)
|
||||
}
|
||||
return true
|
||||
}()
|
||||
if changed {
|
||||
s.logger.Info("已异步接收定时静默续期迟到 Cookie", "account", cookieID)
|
||||
if restarter, ok := s.starter.(accountRestarter); ok {
|
||||
enabled, _, statusErr := s.store.Cookies.StatusWithReason(ctx, cookieID)
|
||||
enabled, _, statusErr := s.store.Cookies.StatusWithReason(opCtx, cookieID)
|
||||
if statusErr != nil {
|
||||
s.logger.Warn("迟到续期 Cookie 已保存,但读取账号状态失败", "account", cookieID, "err", statusErr)
|
||||
return
|
||||
}
|
||||
if !enabled {
|
||||
finalErr = statusErr
|
||||
} else if !enabled {
|
||||
s.logger.Info("迟到续期 Cookie 已保存,账号已停用,不执行重启", "account", cookieID)
|
||||
return
|
||||
}
|
||||
s.logger.Info("迟到续期 Cookie 已更新,正在重启账号以应用最新登录凭证", "account", cookieID)
|
||||
if restartErr := restarter.Restart(ctx, cookieID); restartErr != nil {
|
||||
s.logger.Warn("迟到续期 Cookie 已保存,但重启账号失败", "account", cookieID, "err", restartErr)
|
||||
} else {
|
||||
s.logger.Info("迟到续期 Cookie 更新后的账号重启已完成", "account", cookieID)
|
||||
s.logger.Info("迟到续期 Cookie 已更新,正在重启账号以应用最新登录凭证", "account", cookieID)
|
||||
if restartErr := restarter.Restart(opCtx, cookieID); restartErr != nil {
|
||||
s.logger.Warn("迟到续期 Cookie 已保存,但重启账号失败", "account", cookieID, "err", restartErr)
|
||||
finalErr = restartErr
|
||||
} else {
|
||||
s.logger.Info("迟到续期 Cookie 更新后的账号重启已完成", "account", cookieID)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(opCtx, cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("定时静默续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
finalErr = errors.Join(finalErr, waitErr)
|
||||
}
|
||||
status := "failed"
|
||||
errorMessage := ""
|
||||
if finalErr != nil {
|
||||
errorMessage = finalErr.Error()
|
||||
} else if late.Success {
|
||||
if changed {
|
||||
status = "cookie_updated"
|
||||
} else {
|
||||
status = "success"
|
||||
}
|
||||
} else {
|
||||
errorMessage = late.Message
|
||||
}
|
||||
s.addAPILog(opCtx, db.RenewalLog{
|
||||
BatchID: batchID, CookieID: cookieID, Status: status, Message: late.Message,
|
||||
ErrorMessage: errorMessage, UpdatedCookieNames: late.UpdatedCookieNames,
|
||||
ResponseContent: late.ResponseText, RenewMethod: late.RenewMethod,
|
||||
RequestCount: late.RequestCount,
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Scheduler) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if s == nil || s.store == nil || s.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := s.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
s.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
return
|
||||
}
|
||||
s.logger.Info("Cookie 更新后已唤醒待恢复自动化任务", "account", cookieID)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Scheduler) settingConfigured(ctx context.Context, key string) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return false
|
||||
}
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
return err == nil && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) (db.RenewalAccount, error) {
|
||||
detail, err := s.store.Cookies.GetDetails(ctx, account.ID)
|
||||
if err != nil || detail == nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package renewal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -48,6 +49,23 @@ func (f *schedulerFakeStarter) Restart(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type schedulerContextStarter struct {
|
||||
restarts atomic.Int32
|
||||
ctxAlive atomic.Bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *schedulerContextStarter) Start(context.Context, string, string) error { return nil }
|
||||
|
||||
func (f *schedulerContextStarter) Restart(ctx context.Context, _ string) error {
|
||||
f.restarts.Add(1)
|
||||
f.ctxAlive.Store(ctx.Err() == nil)
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
type schedulerFakePasswordRefresher struct {
|
||||
calls atomic.Int32
|
||||
}
|
||||
@@ -171,6 +189,149 @@ func TestPendingAPIRenewLogsPendingAndRestartsAfterLateCookie(t *testing.T) {
|
||||
if !strings.Contains(detail.Value, "sdkSilent=") {
|
||||
t.Fatalf("迟到 Cookie 未保存: %q", detail.Value)
|
||||
}
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "cookie_updated" {
|
||||
t.Fatalf("迟到响应最终状态=%q want cookie_updated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICookieRenewSuccessWithoutCredentialChangeDoesNotRestart(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
account := createSchedulerAccount(t, store, "cid-no-change", "unb=1; havana_lgc_exp="+expire)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerFakeStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-no-change", account)
|
||||
if got := starter.restarts.Load(); got != 0 {
|
||||
t.Fatalf("Cookie 未变化时不应重启账号,restarts=%d", got)
|
||||
}
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "success" {
|
||||
t.Fatalf("无变化成功状态=%q want success", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewUsesFreshContextForRestart(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
account := createSchedulerAccount(t, store, "cid-fresh-context", "unb=1; havana_lgc_exp="+expire)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureSchedulerMillis(), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerContextStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-context", account)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for starter.restarts.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if starter.restarts.Load() != 1 || !starter.ctxAlive.Load() {
|
||||
t.Fatalf("迟到响应重启必须使用独立有效上下文: restarts=%d alive=%v", starter.restarts.Load(), starter.ctxAlive.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewStopsWithSchedulerContext(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
account := createSchedulerAccount(t, store, "cid-canceled-pending", "unb=1; havana_lgc_exp="+futureSchedulerMillis())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureSchedulerMillis(), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerFakeStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s.apiCookieRenewOne(ctx, "batch-canceled-pending", account)
|
||||
cancel()
|
||||
s.watchers.Wait()
|
||||
if got := starter.restarts.Load(); got != 0 {
|
||||
t.Fatalf("调度器关闭后迟到响应不得重启账号,restarts=%d", got)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(context.Background(), account.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(detail.Value, "sdkSilent=") {
|
||||
t.Fatalf("调度器关闭后不应再写入迟到 Cookie: %q", detail.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewRestartFailureIsFinalFailure(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
account := createSchedulerAccount(t, store, "cid-restart-failure", "unb=1; havana_lgc_exp="+futureSchedulerMillis())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureSchedulerMillis(), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerContextStarter{err: errors.New("restart failed")}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-restart-failure", account)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
log := lastAPIRenewLog(t, store, account.ID)
|
||||
if log.status != "pending" {
|
||||
if log.status != "failed" || !strings.Contains(log.errorMessage, "restart failed") {
|
||||
t.Fatalf("重启失败终态异常: %+v", log)
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("迟到续期没有写入重启失败终态")
|
||||
}
|
||||
|
||||
func futureSchedulerMillis() string {
|
||||
return strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
}
|
||||
|
||||
func TestAPIRenewCompatibilitySettingsUseSingleRunner(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
expire := futureSchedulerMillis()
|
||||
createSchedulerAccount(t, store, "cid-single-runner", "unb=1; havana_lgc_exp="+expire)
|
||||
for _, key := range []string{apiCookieRenewEnabledSetting, cookiesRefreshEnabledSetting} {
|
||||
if err := store.Settings.Set(ctx, key, "true"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.Settings.Set(ctx, apiCookieRenewIntervalSetting, "10s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var requests atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
s.Run(ctx)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for requests.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
if got := requests.Load(); got != 1 {
|
||||
t.Fatalf("新旧配置同时开启只能启动一个续期任务,请求数=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
|
||||
|
||||
@@ -183,6 +183,7 @@ func (s *Server) updateFlatCookieOwnedLocked(ctx context.Context, detail *db.Coo
|
||||
}
|
||||
|
||||
func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
|
||||
s.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
if s.Manager == nil || !s.Store.Cookies.GetStatus(ctx, cookieID) {
|
||||
return
|
||||
}
|
||||
@@ -191,6 +192,15 @@ func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if s == nil || s.Store == nil || s.Store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := s.Store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string {
|
||||
if detail == nil {
|
||||
return ""
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
@@ -418,6 +419,28 @@ func TestUpdateCookie(t *testing.T) {
|
||||
requireCookieSnapshotCleared(t, store, "acc1")
|
||||
}
|
||||
|
||||
func TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
dueAt := time.Now().UTC().Add(time.Hour).Unix()
|
||||
if err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{
|
||||
TaskKey: "acc1:credential", CookieID: "acc1", TriggerType: automation.TriggerOrderPaid,
|
||||
TaskJSON: `{}`, DueAt: dueAt, ErrorMessage: "FAIL_SYS_SESSION_EXPIRED",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.Manager = nil
|
||||
srv.updateRunningCookie(ctx, "acc1", "unb=123; _m_h5_tk=fresh_1;")
|
||||
var got int64
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key=?`, "acc1:credential").Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != 0 {
|
||||
t.Fatalf("Cookie 更新后凭证失败任务 due_at=%d want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCookieQRLoginEnablesAccount(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -21,8 +22,16 @@ type stubPublishMTop struct {
|
||||
}
|
||||
|
||||
func TestRecommendItemPublishCategory(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := srv.Manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Tokens.Save(context.Background(), "acc1", "device", "stale-token", time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := mtop.NewClient()
|
||||
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.URL.Query().Get("api") != "mtop.taobao.idle.kgraph.property.recommend" {
|
||||
@@ -30,7 +39,9 @@ func TestRecommendItemPublishCategory(t *testing.T) {
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Header: http.Header{"Set-Cookie": []string{
|
||||
"_m_h5_tk=recommended_2; Domain=.goofish.com; Path=/; Secure",
|
||||
}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"50023914","catName":"电子资料","channelCatId":"202036301","isClicked":"1"}]}}]}}`,
|
||||
)),
|
||||
@@ -57,6 +68,14 @@ func TestRecommendItemPublishCategory(t *testing.T) {
|
||||
if response.Category.CatID != "50023914" || response.Category.CatName != "电子资料" || response.Category.ChannelCatID != "202036301" {
|
||||
t.Fatalf("category=%+v", response.Category)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(context.Background(), "acc1")
|
||||
if err != nil || !strings.Contains(saved, "_m_h5_tk=recommended_2") {
|
||||
t.Fatalf("类目推荐响应 Cookie 未保存: value=%q err=%v", saved, err)
|
||||
}
|
||||
token, err := store.Tokens.Get(context.Background(), "acc1")
|
||||
if err != nil || token.AccessToken != "" {
|
||||
t.Fatalf("类目推荐 Cookie 更新后未同步运行时并清理旧 token: token=%+v err=%v", token, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubPublishMTop) PublishItem(ctx context.Context, cookies string, req mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
|
||||
@@ -128,7 +128,13 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
|
||||
defer credentialUnlock()
|
||||
runtimeCookie := ""
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if runtimeCookie != "" {
|
||||
s.updateRunningCookie(context.Background(), req.CookieID, runtimeCookie)
|
||||
}
|
||||
}()
|
||||
latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
|
||||
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
|
||||
@@ -138,7 +144,7 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
|
||||
defer cancel()
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, req.Keyword)
|
||||
_, _, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
|
||||
return
|
||||
@@ -148,6 +154,9 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
|
||||
return
|
||||
}
|
||||
runtimeCookie = updatedCookies
|
||||
} else if handled && valueChanged {
|
||||
runtimeCookie = value
|
||||
}
|
||||
if callErr != nil {
|
||||
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
|
||||
@@ -543,6 +552,16 @@ func (s *Server) RunPublishBatchRecovery(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// StartPublishBatchRecovery 先登记生命周期,再启动恢复循环,避免关闭流程在
|
||||
// goroutine 尚未调度时误判扫描器已经退出。
|
||||
func (s *Server) StartPublishBatchRecovery(ctx context.Context) {
|
||||
s.recoveryWG.Add(1)
|
||||
go func() {
|
||||
defer s.recoveryWG.Done()
|
||||
s.RunPublishBatchRecovery(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Server) recoverPublishBatchesOnce(ctx context.Context) {
|
||||
batches, err := s.Store.PublishBatches.Recoverable(ctx, time.Now().UTC().Unix(), 20)
|
||||
if err != nil {
|
||||
@@ -931,10 +950,8 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
}
|
||||
return published, nil
|
||||
}()
|
||||
if runtimeCookieChanged && s.Manager != nil {
|
||||
if account, running := s.Manager.GetInstance(row.CookieID); running {
|
||||
account.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
s.updateRunningCookie(ctx, row.CookieID, runtimeCookie)
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
|
||||
@@ -534,10 +534,8 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if runtimeCookieChanged && s.Manager != nil {
|
||||
if account, running := s.Manager.GetInstance(cookieID); running {
|
||||
account.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
s.updateRunningCookie(r.Context(), cookieID, runtimeCookie)
|
||||
}
|
||||
if callErr != nil {
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
@@ -779,10 +777,8 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
ok, ret, runtimeCookie, runtimeCookieChanged, err := s.consignWithCurrentCookie(r.Context(), order.CookieID, orderID, sess.UserID)
|
||||
if runtimeCookieChanged && s.Manager != nil {
|
||||
if acc, running := s.Manager.GetInstance(order.CookieID); running {
|
||||
acc.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
s.updateRunningCookie(r.Context(), order.CookieID, runtimeCookie)
|
||||
}
|
||||
if err != nil && !ok {
|
||||
failedCount++
|
||||
|
||||
@@ -265,6 +265,7 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
|
||||
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
|
||||
s.refreshAccountProfile(ctx, d)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
|
||||
@@ -83,3 +83,21 @@ func TestPublishWorkerTrackingWaitsForCompletion(t *testing.T) {
|
||||
t.Fatal("wait did not return after worker completed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
srv.StartPublishBatchRecovery(ctx)
|
||||
cancel()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
srv.WaitForBackground()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("批量发布恢复扫描器关闭后没有退出")
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ type Server struct {
|
||||
workerMu sync.Mutex
|
||||
workerCount int
|
||||
workersDone chan struct{}
|
||||
recoveryWG sync.WaitGroup
|
||||
lifecycleMu sync.RWMutex
|
||||
lifecycleCtx context.Context
|
||||
|
||||
@@ -370,10 +371,18 @@ func (s *Server) Run(ctx context.Context) error {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
return err
|
||||
}
|
||||
s.waitForWorkers(10 * time.Second)
|
||||
return nil
|
||||
}
|
||||
|
||||
// WaitForBackground 等待恢复扫描器先退出,再等待其已经登记的批量 worker。
|
||||
func (s *Server) WaitForBackground() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.recoveryWG.Wait()
|
||||
s.waitForWorkers(10 * time.Second)
|
||||
}
|
||||
|
||||
func closedSignal() chan struct{} {
|
||||
done := make(chan struct{})
|
||||
close(done)
|
||||
|
||||
@@ -343,6 +343,17 @@ const (
|
||||
// It never chains hasLogin/setLoginSettings or escalates to an interactive
|
||||
// login from this proactive renewal path.
|
||||
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
return s.renewAPIFirst(ctx, false, cookiesStr, snapshots...)
|
||||
}
|
||||
|
||||
// RenewAfterSessionExpired 用于服务端已经明确返回 SESSION_EXPIRED 的恢复路径。
|
||||
// sdkSilent 只用于限制健康账号的主动静默续期;它不能阻止一次已经被业务接口
|
||||
// 证实为失效的凭证恢复。长登录凭证本身过期时仍拒绝请求并要求重新扫码。
|
||||
func (s Service) RenewAfterSessionExpired(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
return s.renewAPIFirst(ctx, true, cookiesStr, snapshots...)
|
||||
}
|
||||
|
||||
func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
cookiesStr = strings.TrimSpace(cookiesStr)
|
||||
authoritativeSnapshot := len(snapshots) > 0 && snapshots[0] != nil
|
||||
documentURL := s.documentReferer()
|
||||
@@ -384,6 +395,11 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
return result, nil
|
||||
}
|
||||
mode, skipReason := autoLoginMode(firstCookieValues(decisionCookies), now)
|
||||
if sessionExpired && skipReason == "fatigue" {
|
||||
// 业务接口已明确证明 Session 失效,忽略主动续期疲劳标记,但仍只调用
|
||||
// 一次 silentHasLogin,且继续要求长登录凭证有效。
|
||||
mode, skipReason = autoLoginModeWithoutFatigue(firstCookieValues(decisionCookies), now)
|
||||
}
|
||||
if skipReason != "" {
|
||||
result.Skipped = true
|
||||
result.SkipReason = skipReason
|
||||
@@ -472,7 +488,9 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
late.CookieSnapshot = append([]cookierefresh.BrowserCookie(nil), snapshot...)
|
||||
late.CookieSnapshotComplete = true
|
||||
}
|
||||
late, lateErr := populate(late, outcome.call, outcome.err, true)
|
||||
// Promise 超时只描述前端等待窗口;底层响应到达后必须按真实
|
||||
// HTTP/业务结果生成终态,不能永久标记为失败。
|
||||
late, lateErr := populate(late, outcome.call, outcome.err, false)
|
||||
pending <- pendingRenewResult{result: late, err: lateErr}
|
||||
close(pending)
|
||||
}()
|
||||
@@ -481,6 +499,16 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
return populate(result, call, err, false)
|
||||
}
|
||||
|
||||
func autoLoginModeWithoutFatigue(cookies map[string]string, now time.Time) (mode, skipReason string) {
|
||||
if cookieTimeAfter(cookies["havana_lgc_exp"], now) {
|
||||
return autoLoginModeHavana, ""
|
||||
}
|
||||
if cookieTimeAfter(cookies["cookie3_bak_exp"], now) {
|
||||
return autoLoginModeCookie3, ""
|
||||
}
|
||||
return "", "long_login_expired"
|
||||
}
|
||||
|
||||
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
|
||||
if strictCookieTimeAfter(cookies["sdkSilent"], now) {
|
||||
return "", "fatigue"
|
||||
|
||||
@@ -149,6 +149,35 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAfterSessionExpiredBypassesOnlyFatigue(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
calls.Add(1)
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "recovered"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
now := time.Now()
|
||||
cookies := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)
|
||||
service := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
proactive, err := service.RenewAPIFirst(context.Background(), cookies)
|
||||
if err != nil || !proactive.Skipped || proactive.SkipReason != "fatigue" || calls.Load() != 0 {
|
||||
t.Fatalf("proactive=%+v calls=%d err=%v", proactive, calls.Load(), err)
|
||||
}
|
||||
recovered, err := service.RenewAfterSessionExpired(context.Background(), cookies)
|
||||
if err != nil || !recovered.Success || calls.Load() != 1 || !strings.Contains(recovered.NewCookies, "havana_lgc2_77=recovered") {
|
||||
t.Fatalf("recovered=%+v calls=%d err=%v", recovered, calls.Load(), err)
|
||||
}
|
||||
|
||||
expiredLongLogin := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)
|
||||
blocked, err := service.RenewAfterSessionExpired(context.Background(), expiredLongLogin)
|
||||
if err != nil || !blocked.Skipped || blocked.SkipReason != "long_login_expired" || calls.Load() != 1 {
|
||||
t.Fatalf("blocked=%+v calls=%d err=%v", blocked, calls.Load(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -574,8 +603,8 @@ func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
|
||||
if lateErr != nil || late == nil || len(late.SetCookies) != 1 || !strings.Contains(late.NewCookies, "sdkSilent=") {
|
||||
t.Fatalf("迟到响应 Cookie 丢失: result=%+v err=%v", late, lateErr)
|
||||
}
|
||||
if !completed.Load() || late.Success || late.NeedPasswordLogin {
|
||||
t.Fatalf("底层请求应完成,但不得在 Promise 超时后触发成功 reload/重新登录: %+v completed=%v", late, completed.Load())
|
||||
if !completed.Load() || !late.Success || late.NeedPasswordLogin {
|
||||
t.Fatalf("底层请求完成后应返回真实业务终态: %+v completed=%v", late, completed.Load())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user