修复 Cookie 续期终态与账号恢复链路
This commit is contained in:
1 parent
50d09eb47a
commit
5f4d199231
11 files changed
+430
-77
No files matched your search
+34
-44
@@ -564,9 +564,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 +607,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)
|
||||
|
||||
@@ -403,6 +403,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)
|
||||
|
||||
@@ -695,6 +695,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 +812,54 @@ 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)
|
||||
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 +872,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}
|
||||
}
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -91,10 +91,29 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
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)
|
||||
// cookies_refresh 仅作为旧配置名的兼容别名。两套配置必须汇聚到同一个
|
||||
// goroutine,否则同时开启时会重复续期并连续重启同一账号。
|
||||
go s.runAPICookieRenewFixed(ctx)
|
||||
}
|
||||
|
||||
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)) {
|
||||
@@ -259,7 +278,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
return
|
||||
}
|
||||
if res.HasPending() {
|
||||
s.watchPendingAPIRenew(account.ID, res)
|
||||
s.watchPendingAPIRenew(batchID, account.ID, res)
|
||||
}
|
||||
stepDetails := make([]string, 0, len(res.StepDetails)+1)
|
||||
for _, step := range res.StepDetails {
|
||||
@@ -267,12 +286,16 @@ 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 {
|
||||
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
|
||||
@@ -287,7 +310,7 @@ 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
|
||||
@@ -338,70 +361,118 @@ func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []c
|
||||
return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
|
||||
}
|
||||
|
||||
func (s *Scheduler) watchPendingAPIRenew(cookieID string, result *apirenew.Result) {
|
||||
func (s *Scheduler) watchPendingAPIRenew(batchID, cookieID string, result *apirenew.Result) {
|
||||
if result == nil || !result.HasPending() || s.store == nil || s.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), 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"})
|
||||
}
|
||||
return
|
||||
}
|
||||
opCtx, opCancel := context.WithTimeout(context.Background(), 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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) 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"
|
||||
@@ -36,6 +37,7 @@ func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
|
||||
type schedulerFakeStarter struct {
|
||||
starts atomic.Int32
|
||||
restarts atomic.Int32
|
||||
ctxAlive atomic.Bool
|
||||
}
|
||||
|
||||
func (f *schedulerFakeStarter) Start(context.Context, string, string) error {
|
||||
@@ -48,6 +50,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 +190,120 @@ 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 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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -472,7 +472,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)
|
||||
}()
|
||||
|
||||
@@ -574,8 +574,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