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

This commit is contained in:
Christ committed 2026-08-15 05:20:40 +08:00
1 parent 8c16e7810c
commit 73a63eecce
5 files changed
+202 -1155

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -632,3 +632,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 10 第六个 PR 切片“Go internal/xianyu 注释基线按领域清零” | 为 MTOP 请求、协议编解码与签名、二维码登录、续期、WebSocket、Cookie 刷新和用户代理代码及其测试补齐函数、变量、字段和常量中文注释;`internal/xianyu` 及子包注释基线清零;平台协议定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/engine、internal/automation 与其他领域注释基线 |
| 2026-08-15 | 完成阶段 10 第七个 PR 切片“Go internal/engine 注释基线按领域清零” | 为账号运行时、连接循环、凭证作用域、消息分发、回复策略、AI、令牌缓存和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/engine` 注释基线清零;Engine 定向测试、`go test -race ./internal/engine`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/automation、internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
| 2026-08-15 | 完成阶段 10 第八个 PR 切片“Go internal/automation 注释基线按领域清零” | 为自动化中心、账号任务、动作执行器、事件流水线、运行协调器、调度器、通知器及其测试补齐函数、变量、字段和常量中文注释;`internal/automation` 注释基线清零;Automation 定向测试、`go test -race ./internal/automation`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
| 2026-08-15 | 完成阶段 10 第九个 PR 切片“Go internal/account 注释基线按领域清零” | 为账号管理器、凭证作用域、运行时启动/停止和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/account` 注释基线清零;Account 定向测试、`go test -race ./internal/account`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
+21 -2
View File
@@ -28,6 +28,7 @@ type Manager struct {
runCtx context.Context
}
// managedAccount 保存managed账号,供当前处理流程使用
type managedAccount struct {
cookieID string
acc *engine.Account
@@ -51,6 +52,7 @@ func NewManager(store *db.Store, handler engine.Handler, logger *slog.Logger) *M
// StartAll 从 DB 加载所有启用的账号并启动。
// 已禁用的账号不启动;启动失败的账号记录错误但不影响其他账号。
// StartAll 启动All。
func (m *Manager) StartAll(ctx context.Context) error {
m.mu.Lock()
m.runCtx = ctx
@@ -82,7 +84,8 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
if m.runCtx != nil {
ctx = m.runCtx
}
if ma, ok := m.accounts[cookieID]; ok {
if // ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := m.accounts[cookieID]; ok {
// 已存在:若已退出则清理后重启,否则跳过。select 非阻塞,持锁安全。
select {
case <-ma.done:
@@ -93,6 +96,7 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
return nil
}
}
// acc 保存acc,供当前处理流程使用
acc := engine.New(engine.Config{
CookieID: cookieID,
CookieStr: cookieValue,
@@ -100,7 +104,9 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
Handler: m.handler,
Logger: m.logger,
})
// accCtx、cancel 保存accCtx、cancel,供当前处理流程使用
accCtx, cancel := context.WithCancel(ctx)
// ma 保存ma,供当前处理流程使用
ma := &managedAccount{
cookieID: cookieID,
acc: acc,
@@ -112,6 +118,7 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
m.logger.Info("启动账号", "account", cookieID)
go func() {
// err 保存err,供当前处理流程使用
err := acc.Run(accCtx)
m.mu.Lock()
ma.err = err
@@ -125,6 +132,7 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
// Stop 停止单个账号。
func (m *Manager) Stop(cookieID string) {
m.mu.Lock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := m.accounts[cookieID]
m.mu.Unlock()
if !ok {
@@ -134,7 +142,8 @@ func (m *Manager) Stop(cookieID string) {
ma.cancel()
<-ma.done
m.mu.Lock()
if current := m.accounts[cookieID]; current == ma {
if // current 保存current,供当前处理流程使用
current := m.accounts[cookieID]; current == ma {
delete(m.accounts, cookieID)
}
m.mu.Unlock()
@@ -144,9 +153,11 @@ func (m *Manager) Stop(cookieID string) {
// GetInstance 跨层获取账号运行时的消息发送句柄(供 HTTP 手动发货等操作)。
// 返回 automation.MessageSender 接口而非具体 *engine.Account,避免上层
// 直接依赖 engine 包内部类型;*engine.Account 实现该接口。
// GetInstance 读取Instance。
func (m *Manager) GetInstance(cookieID string) (automation.MessageSender, bool) {
m.mu.Lock()
defer m.mu.Unlock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := m.accounts[cookieID]
if !ok {
return nil, false
@@ -161,6 +172,7 @@ func (m *Manager) Sender(cookieID string) (automation.MessageSender, bool) {
// RecoverExpiredCredential 把任意上层 MTOP API 检测到的 Session 失效统一
// 转交给账号 Handler 的协议续期流程。调用方必须先释放账号凭证锁。
// RecoverExpiredCredential 负责RecoverExpiredCredential相关处理。
func (m *Manager) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
if m == nil || m.handler == nil {
return false
@@ -172,8 +184,11 @@ func (m *Manager) RecoverExpiredCredential(ctx context.Context, cookieID string)
func (m *Manager) RuntimeStatuses() map[string]engine.RuntimeStatus {
m.mu.Lock()
defer m.mu.Unlock()
// statuses 保存statuses,供当前处理流程使用
statuses := make(map[string]engine.RuntimeStatus, len(m.accounts))
// id、ma 表示当前遍历过程中的id、ma
for id, ma := range m.accounts {
// status 保存状态,供当前处理流程使用
status := ma.acc.RuntimeStatus()
select {
case <-ma.done:
@@ -205,13 +220,17 @@ func (m *Manager) Restart(ctx context.Context, cookieID string) error {
// StopAll 停止所有运行中的账号,用于进程优雅退出。
// 先在锁内收集 cookieID 列表再解锁逐个停,避免持锁等待 goroutine 退出。
// StopAll 停止All。
func (m *Manager) StopAll() {
m.mu.Lock()
// ids 保存ids,供当前处理流程使用
ids := make([]string, 0, len(m.accounts))
// id 表示当前遍历过程中的标识
for id := range m.accounts {
ids = append(ids, id)
}
m.mu.Unlock()
// id 表示当前遍历过程中的标识
for _, id := range ids {
m.Stop(id)
}
+125 -18
View File
@@ -16,27 +16,41 @@ import (
"xianyu-go/internal/xianyu/ws"
)
// fakeWSDialer 保存fakeWSDialer,供当前处理流程使用
type fakeWSDialer struct{}
// Dial 负责Dial相关处理。
func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) {
return fakeWSConn{}, nil
}
// fakeWSConn 保存fakeWSConn,供当前处理流程使用
type fakeWSConn struct{}
// Register 负责Register相关处理。
func (fakeWSConn) Register(context.Context, string, string) error { return nil }
// HeartbeatLoop 负责HeartbeatLoop相关处理。
func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
<-ctx.Done()
return ctx.Err()
}
// ReceiveLoop 负责ReceiveLoop相关处理。
func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error {
<-ctx.Done()
return ctx.Err()
}
// Close 关闭当前值。
func (fakeWSConn) Close() error { return nil }
// SendText 负责Send文本相关处理。
func (fakeWSConn) SendText(context.Context, string, string, string, string) error {
return nil
}
// SendImage 负责Send图片相关处理。
func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error {
return nil
}
@@ -44,6 +58,7 @@ func (fakeWSConn) SendImage(context.Context, string, string, string, string, int
// fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。
// refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan
// 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。
// fakeMtop 保存fakeMtop,供当前处理流程使用
type fakeMtop struct {
refreshErr error
block chan struct{}
@@ -51,6 +66,7 @@ type fakeMtop struct {
mu sync.Mutex
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (f *fakeMtop) RefreshTokenWithDeviceIDContext(ctx context.Context, _, _ string) (*mtop.RefreshResult, error) {
f.mu.Lock()
f.calls++
@@ -68,18 +84,27 @@ func (f *fakeMtop) RefreshTokenWithDeviceIDContext(ctx context.Context, _, _ str
return &mtop.RefreshResult{AccessToken: "fake-token"}, nil
}
// FetchUserProfile 负责Fetch用户Profile相关处理。
func (f *fakeMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, nil
}
// ConsignContext 负责Consign上下文相关处理。
func (f *fakeMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
return false, nil, "", nil
}
// FetchItemsPage 负责Fetch商品列表页码相关处理。
func (f *fakeMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// FetchAllItems 负责FetchAll商品列表相关处理。
func (f *fakeMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// PublishItem 负责发布商品相关处理。
func (f *fakeMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, nil
}
@@ -87,11 +112,14 @@ func (f *fakeMtop) PublishItem(context.Context, string, mtop.PublishItemRequest)
// newTestStore 构造临时 SQLite + 已初始化的 admin,返回 store 与 cleanup。
func newTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
return store, func() { d.Close() }
@@ -100,13 +128,17 @@ func newTestStore(t *testing.T) (*db.Store, func()) {
// newManagerWithAccount 构造 Manager 并向 DB 写入一个启用的账号。
func newManagerWithAccount(t *testing.T, cookieID, cookieValue string) (*Manager, *db.Store, func()) {
t.Helper()
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
if err := store.Cookies.Save(context.Background(), cookieID, cookieValue, admin.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(context.Background(), cookieID, cookieValue, admin.ID); err != nil {
cleanup()
t.Fatalf("Save cookie: %v", err)
}
if err := store.Cookies.SetStatus(context.Background(), cookieID, true); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.SetStatus(context.Background(), cookieID, true); err != nil {
cleanup()
t.Fatalf("SetStatus: %v", err)
}
@@ -115,9 +147,12 @@ func newManagerWithAccount(t *testing.T, cookieID, cookieValue string) (*Manager
// startAccountWithMtop 用自定义 mtop 客户端启动账号,返回 runCtx 的 cancel。
// runCtx 在测试结束 / Stop 时取消以回收 Run goroutine。
// startAccountWithMtop 负责开始账号WithMtop相关处理。
func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue string, mtopClient mtop.Client) context.CancelFunc {
t.Helper()
// runCtx、cancel 保存运行Ctx、cancel,供当前处理流程使用
runCtx, cancel := context.WithCancel(context.Background())
// acc 保存acc,供当前处理流程使用
acc := engine.New(engine.Config{
CookieID: cookieID,
CookieStr: cookieValue,
@@ -127,7 +162,9 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri
MTop: mtopClient,
WSDialer: fakeWSDialer{},
})
// accCtx、accCancel 保存accCtx、acc取消,供当前处理流程使用
accCtx, accCancel := context.WithCancel(runCtx)
// ma 保存ma,供当前处理流程使用
ma := &managedAccount{
cookieID: cookieID,
acc: acc,
@@ -147,6 +184,7 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri
// TestSender 验证 Sender 在账号在线时返回 MessageSender,离线时返回 false。
func TestSender(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "acc-on", "unb=1; _m_h5_tk=t1_1;")
defer cleanup()
@@ -154,17 +192,20 @@ func TestSender(t *testing.T) {
if s, ok := mgr.Sender("acc-on"); ok || s != nil {
t.Fatalf("未启动账号 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
if s, ok := mgr.Sender("acc-missing"); ok || s != nil {
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-missing"); ok || s != nil {
t.Fatalf("不存在账号 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
// 用阻塞型 mtop 启动,让 Run 一直挂起,账号保持"运行中"。
mtopClient := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "acc-on", "unb=1; _m_h5_tk=t1_1;", mtopClient)
defer cancel()
// 给 Run 一点时间进入 refreshToken 阻塞。
time.Sleep(50 * time.Millisecond)
// s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-on")
if !ok || s == nil {
t.Fatalf("在线账号 Sender 应返回 (sender,true)")
@@ -173,7 +214,8 @@ func TestSender(t *testing.T) {
// 停止后应回到 (nil,false)。Stop 会取消 accCtx,refreshToken 在阻塞 select
// 上收到 ctx.Done() 返回,Run 退出,不会进入真实 WS dial。
mgr.Stop("acc-on")
if s, ok := mgr.Sender("acc-on"); ok || s != nil {
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-on"); ok || s != nil {
t.Fatalf("停止后 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
}
@@ -185,13 +227,18 @@ func TestSender(t *testing.T) {
// - done 已关 + err=context.Canceled:覆盖为 RuntimeError + "账号服务已退出"
// - done 已关 + 状态=RuntimeAuthExpired:保持原状态(通过 session-expired 走 handleMaxFailures)
// - done 已关 + 状态=RuntimeVerificationRequired:保持原状态(通过验证类错误 + 取消)
//
// TestRuntimeStatuses 负责TestRuntimeStatuses相关处理。
func TestRuntimeStatuses(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t1_1;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 1) 运行中账号:阻塞型 mtop 让 Run 挂起。
runMtop := &fakeMtop{block: make(chan struct{})}
// runCancel 保存运行取消,供当前处理流程使用
runCancel := startAccountWithMtop(t, mgr, "running", "unb=10; _m_h5_tk=t_1;", runMtop)
defer runCancel()
time.Sleep(50 * time.Millisecond)
@@ -201,6 +248,7 @@ func TestRuntimeStatuses(t *testing.T) {
CookieID: "nil-done", CookieStr: "unb=2; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// nilDoneMA 保存nilDoneMA,供当前处理流程使用
nilDoneMA := &managedAccount{cookieID: "nil-done", acc: nilDoneAcc, done: make(chan struct{})}
close(nilDoneMA.done) // err 为 nil
mgr.mu.Lock()
@@ -212,6 +260,7 @@ func TestRuntimeStatuses(t *testing.T) {
CookieID: "err-done", CookieStr: "unb=3; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// errDoneMA 保存errDoneMA,供当前处理流程使用
errDoneMA := &managedAccount{cookieID: "err-done", acc: errDoneAcc, done: make(chan struct{}), err: errors.New("boom-failure")}
close(errDoneMA.done)
mgr.mu.Lock()
@@ -223,6 +272,7 @@ func TestRuntimeStatuses(t *testing.T) {
CookieID: "canceled", CookieStr: "unb=4; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// canceledMA 保存canceledMA,供当前处理流程使用
canceledMA := &managedAccount{cookieID: "canceled", acc: canceledAcc, done: make(chan struct{}), err: context.Canceled}
close(canceledMA.done)
mgr.mu.Lock()
@@ -232,7 +282,9 @@ func TestRuntimeStatuses(t *testing.T) {
// 5) 状态=RuntimeAuthExpired(session-expired 错误让 Run 走到 handleMaxFailures 慢重试)。
// 新行为:账号不再硬退出,而是保持 goroutine 存活、慢重试,状态停在 RuntimeAuthExpired。
store.Cookies.Save(context.Background(), "auth-exp", "unb=5; _m_h5_tk=t_1;", admin.ID)
// authMgr 保存authMgr,供当前处理流程使用
authMgr := mgr
// authCancel 保存auth取消,供当前处理流程使用
authCancel := startAccountWithMtop(t, authMgr, "auth-exp", "unb=5; _m_h5_tk=t_1;",
&fakeMtop{refreshErr: errors.New("token API 登录凭证已失效: ret=[FAIL_SYS_SESSION_EXPIRED] status=403")})
defer authCancel()
@@ -243,7 +295,9 @@ func TestRuntimeStatuses(t *testing.T) {
// 6) done 已关 + 状态=RuntimeVerificationRequired(验证类错误 + 立即取消 ctx)。
store.Cookies.Save(context.Background(), "verify", "unb=6; _m_h5_tk=t_1;", admin.ID)
// verifyMtop 保存verifyMtop,供当前处理流程使用
verifyMtop := &fakeMtop{refreshErr: errors.New("FAIL_SYS_USER_VALIDATE: captcha required")}
// verifyCancel 保存verify取消,供当前处理流程使用
verifyCancel := startAccountWithMtop(t, mgr, "verify", "unb=6; _m_h5_tk=t_1;", verifyMtop)
// 让 Run 进入一次 refreshToken → setRuntimeError(RuntimeVerificationRequired) → sleepCtx。
time.Sleep(80 * time.Millisecond)
@@ -252,6 +306,7 @@ func TestRuntimeStatuses(t *testing.T) {
t.Fatal("verify 账号未在超时内退出")
}
// statuses 保存statuses,供当前处理流程使用
statuses := mgr.RuntimeStatuses()
// 运行中:应有该 key,状态非空。
@@ -292,9 +347,11 @@ func TestRuntimeStatuses(t *testing.T) {
// waitForDone 轮询等待某账号 done 关闭。
func waitForDone(mgr *Manager, cookieID string, timeout time.Duration) bool {
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
mgr.mu.Lock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := mgr.accounts[cookieID]
mgr.mu.Unlock()
if !ok {
@@ -312,9 +369,11 @@ func waitForDone(mgr *Manager, cookieID string, timeout time.Duration) bool {
// waitForState 轮询等待某账号进入指定运行时状态。
func waitForState(mgr *Manager, cookieID, want string, timeout time.Duration) bool {
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
mgr.mu.Lock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := mgr.accounts[cookieID]
mgr.mu.Unlock()
if ok && ma.acc != nil && ma.acc.RuntimeStatus().State == want {
@@ -327,16 +386,20 @@ func waitForState(mgr *Manager, cookieID, want string, timeout time.Duration) bo
// TestRestart 验证重启账号:停止旧实例→读取最新 DB cookie→启动新实例。
func TestRestart(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "restart-acc", "unb=1; _m_h5_tk=old;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 用阻塞 mtop 启动旧实例,使其保持运行。
oldMtop := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "restart-acc", "unb=1; _m_h5_tk=old;", oldMtop)
defer cancel()
time.Sleep(50 * time.Millisecond)
// oldMA 保存oldMA,供当前处理流程使用
oldMA, _ := mgr.getInstanceInternal("restart-acc")
if oldMA == nil {
t.Fatal("旧实例应存在")
@@ -345,9 +408,11 @@ func TestRestart(t *testing.T) {
// 更新 DB cookie 为新值,模拟外部刷新。
store.Cookies.Save(context.Background(), "restart-acc", "unb=1; _m_h5_tk=new-refreshed;", admin.ID)
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer ctxCancel()
if err := mgr.Restart(ctx, "restart-acc"); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.Restart(ctx, "restart-acc"); err != nil {
t.Fatalf("Restart: %v", err)
}
@@ -377,11 +442,14 @@ func TestRestart(t *testing.T) {
// TestRestart_GetDetailsError 验证 Restart 读不存在的账号详情应返回包装错误。
func TestRestart_GetDetailsError(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t;")
defer cleanup()
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer ctxCancel()
// err 保存err,供当前处理流程使用
err := mgr.Restart(ctx, "no-such-account")
if err == nil {
t.Fatal("Restart 不存在账号应返回错误")
@@ -393,19 +461,25 @@ func TestRestart_GetDetailsError(t *testing.T) {
// TestStart_SkipsRunning 验证对运行中账号调用 Start 跳过启动。
func TestStart_SkipsRunning(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "running-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
// runMtop 保存运行Mtop,供当前处理流程使用
runMtop := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "running-acc", "unb=1; _m_h5_tk=t;", runMtop)
defer cancel()
time.Sleep(50 * time.Millisecond)
// original 保存original,供当前处理流程使用
original, _ := mgr.getInstanceInternal("running-acc")
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer ctxCancel()
if err := mgr.Start(ctx, "running-acc", "unb=1; _m_h5_tk=different;"); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.Start(ctx, "running-acc", "unb=1; _m_h5_tk=different;"); err != nil {
t.Fatalf("Start 运行中账号应返回 nil,got %v", err)
}
@@ -414,7 +488,8 @@ func TestStart_SkipsRunning(t *testing.T) {
if after != original {
t.Fatal("Start 运行中账号不应替换实例")
}
if got := after.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=t;" {
if // got 保存got,供当前处理流程使用
got := after.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=t;" {
t.Fatalf("实例 CookieStr 不应变,got %q", got)
}
@@ -424,7 +499,9 @@ func TestStart_SkipsRunning(t *testing.T) {
// TestStart_RestartsExited 验证 Manager.Start 在"账号已存在且 done 已关"路径上
// 清理旧实例并重启新实例。该路径曾是双重解锁 bug(分支内 Unlock 后函数末尾再次
// Unlock),已修复:现在持锁 delete 后由函数末尾单次 Unlock。
// TestStart_RestartsExited 负责Test开始RestartsExited相关处理。
func TestStart_RestartsExited(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "exited-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
@@ -433,25 +510,30 @@ func TestStart_RestartsExited(t *testing.T) {
CookieID: "exited-acc", CookieStr: "unb=1; _m_h5_tk=old;",
Store: mgr.store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// exitedMA 保存exitedMA,供当前处理流程使用
exitedMA := &managedAccount{cookieID: "exited-acc", acc: exitedAcc, done: make(chan struct{}), err: context.Canceled}
close(exitedMA.done)
mgr.mu.Lock()
mgr.accounts["exited-acc"] = exitedMA
mgr.mu.Unlock()
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithCancel(context.Background())
defer ctxCancel()
mgr.mu.Lock()
mgr.runCtx = ctx
mgr.mu.Unlock()
if err := mgr.store.Cookies.Save(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;", 0); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.store.Cookies.Save(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;", 0); err != nil {
t.Fatal(err)
}
if err := mgr.Start(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;"); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.Start(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;"); err != nil {
t.Fatalf("Start 已退出账号应成功,got %v", err)
}
// newMA、ok 保存newMA、ok,供当前处理流程使用
newMA, ok := mgr.getInstanceInternal("exited-acc")
if !ok {
t.Fatal("Start 后应存在新实例")
@@ -459,7 +541,8 @@ func TestStart_RestartsExited(t *testing.T) {
if newMA == exitedMA {
t.Fatal("应替换为全新实例")
}
if got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=brand-new;" {
if // got 保存got,供当前处理流程使用
got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=brand-new;" {
t.Fatalf("新实例 CookieStr=%q want brand-new", got)
}
// done 不应已关闭(新实例在运行)。
@@ -474,9 +557,12 @@ func TestStart_RestartsExited(t *testing.T) {
// TestStartAll_LoadError 验证 StartAll 在 DB 加载失败时返回包装错误。
// 通过提前关闭底层 sql.DB 触发运行时凭证查询错误。
// TestStartAll_LoadError 负责Test开始AllLoad错误相关处理。
func TestStartAll_LoadError(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
defer cleanup()
// mgr 保存mgr,供当前处理流程使用
mgr := NewManager(store, noopHandler{}, nil)
// 提前关闭 DB 让 ListEnabledRuntimeCredentials 失败。
@@ -484,8 +570,10 @@ func TestStartAll_LoadError(t *testing.T) {
t.Fatalf("关闭 DB: %v", err)
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx)
if err == nil {
t.Fatal("StartAll 在 DB 加载失败时应返回错误")
@@ -497,8 +585,10 @@ func TestStartAll_LoadError(t *testing.T) {
// TestStartAll_DisabledNotStarted 验证 DB 中禁用的账号不被启动。
func TestStartAll_DisabledNotStarted(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 启用 + 禁用 + 启用。
store.Cookies.Save(context.Background(), "on1", "unb=1; _m_h5_tk=t;", admin.ID)
@@ -510,10 +600,12 @@ func TestStartAll_DisabledNotStarted(t *testing.T) {
// 用阻塞 mtop 的 Manager:直接构造,使所有启动账号都挂起、不触发真实网络。
mgr := NewManager(store, noopHandler{}, nil)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := mgr.StartAll(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx); err != nil {
t.Fatalf("StartAll: %v", err)
}
@@ -521,17 +613,21 @@ func TestStartAll_DisabledNotStarted(t *testing.T) {
if _, ok := mgr.GetInstance("on1"); !ok {
t.Fatal("on1 应被启动")
}
if _, ok := mgr.GetInstance("on2"); !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("on2"); !ok {
t.Fatal("on2 应被启动")
}
if _, ok := mgr.GetInstance("off1"); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("off1"); ok {
t.Fatal("off1 已禁用不应被启动")
}
// StopAll 应清空全部。
mgr.StopAll()
// id 表示当前遍历过程中的标识
for _, id := range []string{"on1", "on2", "off1"} {
if _, ok := mgr.GetInstance(id); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance(id); ok {
t.Fatalf("StopAll 后 %s 仍存在", id)
}
}
@@ -539,6 +635,7 @@ func TestStartAll_DisabledNotStarted(t *testing.T) {
// TestStop_Nonexistent 验证停止不存在的账号是 no-op,不 panic。
func TestStop_Nonexistent(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t;")
defer cleanup()
// 不应 panic。
@@ -547,8 +644,10 @@ func TestStop_Nonexistent(t *testing.T) {
// TestConcurrency 用 -race 验证多 goroutine 并发访问 GetInstance/Sender/RuntimeStatuses 不 race。
func TestConcurrency(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "conc-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 多个启用账号。
for _, id := range []string{"conc-2", "conc-3"} {
@@ -558,30 +657,37 @@ func TestConcurrency(t *testing.T) {
// 用阻塞 mtop 让账号保持运行,避免 Run 退出引入噪声。
for _, id := range []string{"conc-acc", "conc-2", "conc-3"} {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &fakeMtop{block: make(chan struct{})}
// c 保存c,供当前处理流程使用
c := startAccountWithMtop(t, mgr, id, "unb=1; _m_h5_tk=t;", mtopClient)
defer c()
}
time.Sleep(60 * time.Millisecond)
// wg 保存wg,供当前处理流程使用
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 20; i++ {
wg.Add(3)
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_, _ = mgr.GetInstance("conc-acc")
}
}()
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_, _ = mgr.Sender("conc-2")
}
}()
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_ = mgr.RuntimeStatuses()
}
}()
@@ -594,6 +700,7 @@ func TestConcurrency(t *testing.T) {
func (m *Manager) getInstanceInternal(cookieID string) (*managedAccount, bool) {
m.mu.Lock()
defer m.mu.Unlock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := m.accounts[cookieID]
return ma, ok
}
+55 -13
View File
@@ -12,24 +12,37 @@ import (
"xianyu-go/internal/engine"
)
// noopHandler 保存noopHandler,供当前处理流程使用
type noopHandler struct{}
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// HandleChatMessage 处理聊天消息。
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
// HandleSystemEvent 处理系统Event。
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestManagerStartStop 验证从 DB 加载账号、启停和 GetInstance。
// 用无效 cookie 让账号快速进入重连等待(不会真正连上),验证管理逻辑而非网络。
// TestManagerStartStop 负责TestManager开始Stop相关处理。
func TestManagerStartStop(t *testing.T) {
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer d.Close()
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 两个启用 + 一个禁用的账号。
@@ -40,17 +53,21 @@ func TestManagerStartStop(t *testing.T) {
store.Cookies.Save(context.Background(), "acc3", "unb=3; _m_h5_tk=t3_1;", admin.ID)
store.Cookies.SetStatus(context.Background(), "acc3", false)
// mgr 保存mgr,供当前处理流程使用
mgr := NewManager(store, noopHandler{}, nil)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := mgr.StartAll(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx); err != nil {
t.Fatalf("StartAll: %v", err)
}
// acc1/acc2 应有运行实例,acc3 不应。
for _, id := range []string{"acc1", "acc2"} {
if acc, ok := mgr.GetInstance(id); !ok || acc == nil {
if // acc、ok 保存acc、ok,供当前处理流程使用
acc, ok := mgr.GetInstance(id); !ok || acc == nil {
t.Fatalf("GetInstance(%s) 失败", id)
}
}
@@ -59,48 +76,62 @@ func TestManagerStartStop(t *testing.T) {
if acc, ok := mgr.GetInstance("acc1"); !ok || acc == nil {
t.Fatal("GetInstance(acc1) 失败")
}
if _, ok := mgr.GetInstance("acc3"); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("acc3"); ok {
t.Fatal("acc3 不应有实例")
}
// Stop 应能干净停止。
mgr.Stop("acc1")
mgr.Stop("acc2")
if _, ok := mgr.GetInstance("acc1"); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("acc1"); ok {
t.Fatal("Stop 后 acc1 仍存在")
}
if _, ok := mgr.GetInstance("acc2"); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("acc2"); ok {
t.Fatal("Stop 后 acc2 仍存在")
}
}
// TestManagerConcurrentStartCreatesSingleManagedInstance 负责TestManagerConcurrent开始CreatesSingleManagedInstance相关处理。
func TestManagerConcurrentStartCreatesSingleManagedInstance(t *testing.T) {
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// database、err 保存database、err,供当前处理流程使用
database, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer database.Close()
// store 保存store,供当前处理流程使用
store := db.NewStore(database, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "same", "unb=1; _m_h5_tk=t_1;", admin.ID)
// mgr 保存mgr,供当前处理流程使用
mgr := NewManager(store, noopHandler{}, nil)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// wg 保存wg,供当前处理流程使用
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := mgr.Start(ctx, "same", "unb=1; _m_h5_tk=t_1;"); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.Start(ctx, "same", "unb=1; _m_h5_tk=t_1;"); err != nil {
t.Errorf("Start: %v", err)
}
}()
}
wg.Wait()
mgr.mu.Lock()
// count 保存数量,供当前处理流程使用
count := len(mgr.accounts)
mgr.mu.Unlock()
if count != 1 {
@@ -111,14 +142,18 @@ func TestManagerConcurrentStartCreatesSingleManagedInstance(t *testing.T) {
// TestManagerStopAll 验证 StopAll 停止所有运行中的账号,用于进程优雅退出。
func TestManagerStopAll(t *testing.T) {
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer d.Close()
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 三个启用账号。
for _, id := range []string{"a1", "a2", "a3"} {
@@ -126,22 +161,29 @@ func TestManagerStopAll(t *testing.T) {
store.Cookies.SetStatus(context.Background(), id, true)
}
// mgr 保存mgr,供当前处理流程使用
mgr := NewManager(store, noopHandler{}, nil)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := mgr.StartAll(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx); err != nil {
t.Fatalf("StartAll: %v", err)
}
// id 表示当前遍历过程中的标识
for _, id := range []string{"a1", "a2", "a3"} {
if _, ok := mgr.GetInstance(id); !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance(id); !ok {
t.Fatalf("GetInstance(%s) 失败", id)
}
}
// StopAll 应清空全部实例。
mgr.StopAll()
// id 表示当前遍历过程中的标识
for _, id := range []string{"a1", "a2", "a3"} {
if _, ok := mgr.GetInstance(id); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance(id); ok {
t.Fatalf("StopAll 后 %s 仍存在", id)
}
}