修复 WS Token 主动轮换与自动化任务恢复
根据服务端过期时间提前轮换 WS Token,并对缺失期限使用保守刷新窗口。 Token 获取瞬时失败时保持账号运行并在过期前持续重试;统一 Cookie、WS 恢复后的自动化唤醒和安全动作游标重试。 修复多实例恢复租约覆盖、规则查询误隔离及人工核对状态落库错误,并等待自动化调度器、续期 watcher 和批量发布恢复任务优雅退出。 补充 SQLite、PostgreSQL 17、生命周期和竞态回归测试。
This commit is contained in:
1 parent
9c742f5e7f
commit
bdc64c68f6
24 files changed
+1080
-110
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()
|
||||
|
||||
@@ -350,7 +350,6 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
if !a.OnPasswordLoginRefresh(ctx, cookieID) {
|
||||
return nil, fmt.Errorf("订单详情 Session 过期且即时续期失败: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.logger.Info("Cookie 即时续期成功,重新请求订单详情", "account", cookieID, "order_id", orderID)
|
||||
return a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
}
|
||||
@@ -401,6 +400,7 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
}
|
||||
if fetchErr != nil {
|
||||
@@ -414,6 +414,7 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
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,
|
||||
@@ -477,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
|
||||
}
|
||||
@@ -490,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()
|
||||
|
||||
+100
-14
@@ -19,6 +19,8 @@ import (
|
||||
var (
|
||||
errAutomationDeferred = errors.New("自动化动作已持久化等待执行")
|
||||
errAutomationNeedsReview = errors.New("自动化动作结果需要人工核对")
|
||||
errAutomationQuarantine = errors.New("自动化人工核对状态保存失败")
|
||||
errActionNotPerformed = errors.New("自动化外部动作明确未执行")
|
||||
// ErrMessageNotSent 表示错误发生在调用 WebSocket 发送之前,可以安全重试。
|
||||
// engine 通过 errors.Is 标记“连接尚未就绪”等运行时状态,避免被误判为
|
||||
// 远端可能已经收到消息。
|
||||
@@ -71,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)
|
||||
@@ -82,6 +89,7 @@ type Center struct {
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
logger *slog.Logger
|
||||
@@ -103,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 注入发货结果通知器。
|
||||
@@ -132,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
|
||||
@@ -458,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)
|
||||
@@ -474,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)
|
||||
@@ -551,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
|
||||
@@ -774,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() {
|
||||
@@ -839,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...))
|
||||
@@ -872,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
|
||||
@@ -898,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) == "" {
|
||||
@@ -925,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)
|
||||
}
|
||||
}
|
||||
@@ -935,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 {
|
||||
@@ -1044,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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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("自动化调度器关闭后没有退出")
|
||||
}
|
||||
}
|
||||
+27
-12
@@ -12,6 +12,9 @@ import (
|
||||
|
||||
var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行")
|
||||
|
||||
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
|
||||
const SafeRetryErrorPrefix = "[safe_retry]"
|
||||
|
||||
// AutomationRules 管理自动化规则、动作和执行记录。
|
||||
//
|
||||
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
|
||||
@@ -442,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
|
||||
@@ -536,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
|
||||
}
|
||||
@@ -560,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, `
|
||||
@@ -596,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
|
||||
@@ -875,14 +885,19 @@ func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID st
|
||||
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%')`, cookieID); err != nil {
|
||||
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 sent_count=0 AND action_started=0
|
||||
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%')`, cookieID)
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -681,6 +712,15 @@ func TestDeferredRetryBackoffAndCredentialWake(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -639,6 +639,74 @@ func TestMultiDB_DeferredAutomationCredentialWake(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
+152
-26
@@ -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()
|
||||
@@ -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()
|
||||
@@ -854,6 +919,7 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
}
|
||||
a.replaceCredentialState(value, credentialStateFingerprint(value, metadata))
|
||||
a.clearTokenCache(ctx)
|
||||
a.notifyCredentialUpdated(ctx)
|
||||
if err != nil {
|
||||
a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err)
|
||||
}
|
||||
@@ -933,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
|
||||
@@ -970,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)
|
||||
@@ -1007,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 {
|
||||
@@ -1055,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
|
||||
}
|
||||
@@ -1082,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 {
|
||||
@@ -1343,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 {
|
||||
@@ -1454,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
|
||||
}
|
||||
@@ -1562,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) {
|
||||
|
||||
+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")
|
||||
|
||||
@@ -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,12 +94,34 @@ 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 疲劳窗口仍会在请求前阻止重复续期。
|
||||
// cookies_refresh 仅作为旧配置名的兼容别名。两套配置必须汇聚到同一个
|
||||
// goroutine,否则同时开启时会重复续期并连续重启同一账号。
|
||||
go s.runAPICookieRenewFixed(ctx)
|
||||
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) {
|
||||
@@ -159,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 {
|
||||
@@ -203,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))
|
||||
@@ -224,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))
|
||||
@@ -251,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)
|
||||
@@ -278,7 +324,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
return
|
||||
}
|
||||
if res.HasPending() {
|
||||
s.watchPendingAPIRenew(batchID, account.ID, res)
|
||||
s.watchPendingAPIRenew(ctx, batchID, account.ID, res)
|
||||
}
|
||||
stepDetails := make([]string, 0, len(res.StepDetails)+1)
|
||||
for _, step := range res.StepDetails {
|
||||
@@ -286,7 +332,6 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
}
|
||||
stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason))
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
|
||||
credentialChanged := false
|
||||
if res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != account.Value {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if res.CookieSnapshotComplete {
|
||||
@@ -300,6 +345,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
s.logger.Warn("接口续期任务失败", "account", account.ID, "method", res.RenewMethod, "err", "保存 Cookie 失败")
|
||||
return
|
||||
}
|
||||
credentialPersisted = credentialChanged
|
||||
}
|
||||
if callErr != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{
|
||||
@@ -315,6 +361,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
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})
|
||||
@@ -323,7 +370,6 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
}
|
||||
s.logger.Info("接口续期后的账号重启已完成", "account", account.ID)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
}
|
||||
status := "failed"
|
||||
if res.HasPending() {
|
||||
@@ -356,28 +402,44 @@ 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(batchID, 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() {
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
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(context.Background(), db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: "failed", ErrorMessage: waitErr.Error(), RenewMethod: "auto_login_plugin"})
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: "failed", ErrorMessage: waitErr.Error(), RenewMethod: "auto_login_plugin"})
|
||||
}
|
||||
return
|
||||
}
|
||||
opCtx, opCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
opCtx, opCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer opCancel()
|
||||
var finalErr error
|
||||
changed := func() bool {
|
||||
|
||||
@@ -239,6 +239,35 @@ func TestPendingAPIRenewUsesFreshContextForRestart(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -552,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 {
|
||||
@@ -940,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)
|
||||
|
||||
Reference in new issue
Block a user