阶段六:修复生命周期与运行状态一致性
This commit is contained in:
1 parent
5f8d999ab0
commit
c23a5a18b8
43 files changed
+1541
-171
No files matched your search
@@ -65,7 +65,7 @@ type OrdersPort interface {
|
||||
|
||||
// OrderRefreshJobsPort 定义订单刷新任务 HTTP 接口所需的最小能力。
|
||||
type OrderRefreshJobsPort interface {
|
||||
CreateAndStart(context.Context, context.Context, int64, string, string) (orderapp.RefreshJobStartResult, error)
|
||||
CreateAndStart(context.Context, int64, string, string) (orderapp.RefreshJobStartResult, error)
|
||||
GetJob(context.Context, int64, string) (*orderapp.RefreshJob, error)
|
||||
CancelForUser(context.Context, int64, string) (orderapp.RefreshJobCancelResult, error)
|
||||
}
|
||||
|
||||
@@ -243,42 +243,15 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if settingsResult.RuntimeError != nil && s.Logger != nil {
|
||||
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", settingsResult.RuntimeError)
|
||||
}
|
||||
if settingsResult.RuntimeError != nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "账号设置已保存,但运行实例重启失败,请重试启用账号")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cookieSettingsResponse{
|
||||
Success: true, PausedUntil: settingsResult.PausedUntil, Paused: settingsResult.PausedUntil > time.Now().UTC().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API,可安全用于前端轮询。
|
||||
func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
|
||||
accountSummary := s.accountSummaryApplication()
|
||||
cookieIDs, err := accountSummary.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号失败")
|
||||
return
|
||||
}
|
||||
// runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。
|
||||
runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context())
|
||||
if runtimeErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败")
|
||||
return
|
||||
}
|
||||
result := make(map[string]accountapp.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。
|
||||
for _, cid := range cookieIDs { // cid 是当前账号 ID。
|
||||
enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid)
|
||||
if statusErr != nil || !enabled {
|
||||
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
|
||||
continue
|
||||
}
|
||||
if status, ok := runtime[cid]; ok { // status 和 ok 表示已记录的运行状态及存在性。
|
||||
result[cid] = status
|
||||
continue
|
||||
}
|
||||
result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// listCookies 列出当前用户的 cookie_id。
|
||||
func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
|
||||
@@ -567,8 +540,16 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
if result.RuntimeError != nil && s.Logger != nil {
|
||||
s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError)
|
||||
if result.RuntimeError != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError)
|
||||
}
|
||||
if errors.Is(result.RuntimeError, accountapp.ErrRuntimeStopConflict) {
|
||||
writeErr(w, http.StatusConflict, "账号运行实例尚未停止,请稍后重试")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusServiceUnavailable, "账号运行实例启动失败,请重试")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
@@ -19,6 +19,92 @@ import (
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// runtimeStatusPortStub 是运行状态 HTTP 契约测试的最小应用 Port,不持有真实账号实例或凭证。
|
||||
type runtimeStatusPortStub struct {
|
||||
// statuses 保存按账号标识返回的非敏感运行时快照。
|
||||
statuses map[string]accountapp.RuntimeStatus
|
||||
}
|
||||
|
||||
// UpdateCookie 满足运行状态 Port;本测试不触发 Cookie 同步。
|
||||
func (stub runtimeStatusPortStub) UpdateCookie(context.Context, string, string) error { return nil }
|
||||
|
||||
// RuntimeStatuses 返回预置快照,模拟数据库状态与运行实例状态暂时不一致。
|
||||
func (stub runtimeStatusPortStub) RuntimeStatuses(context.Context) (map[string]accountapp.RuntimeStatus, error) {
|
||||
return stub.statuses, nil
|
||||
}
|
||||
|
||||
// Restart 满足运行状态 Port;本测试不触发运行实例重启。
|
||||
func (stub runtimeStatusPortStub) Restart(context.Context, string) error { return nil }
|
||||
|
||||
// RecoverExpiredCredential 满足运行状态 Port;本测试不触发平台凭证恢复。
|
||||
func (stub runtimeStatusPortStub) RecoverExpiredCredential(context.Context, string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// TestRuntimeStatusIsActive 保证已停用账号的存活运行实例不会被状态查询掩盖为普通 disabled。
|
||||
func TestRuntimeStatusIsActive(t *testing.T) {
|
||||
// cases 保存运行状态与是否仍需暴露冲突诊断的对应关系。
|
||||
cases := []struct {
|
||||
name string
|
||||
status accountapp.RuntimeStatus
|
||||
wantAlive bool
|
||||
}{
|
||||
{name: "connected", status: accountapp.RuntimeStatus{Connected: true}, wantAlive: true},
|
||||
{name: "connecting", status: accountapp.RuntimeStatus{State: "connecting"}, wantAlive: true},
|
||||
{name: "exited", status: accountapp.RuntimeStatus{State: "error", Message: "账号服务已退出"}, wantAlive: false},
|
||||
{name: "stopped", status: accountapp.RuntimeStatus{State: "stopped"}, wantAlive: false},
|
||||
}
|
||||
// testCase 是当前验证的运行状态样本。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// got 是当前样本是否必须向管理页面暴露运行时冲突的判断结果。
|
||||
if got := runtimeStatusIsActive(testCase.status); got != testCase.wantAlive {
|
||||
t.Fatalf("runtimeStatusIsActive(%+v)=%v, want %v", testCase.status, got, testCase.wantAlive)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookieRuntimeStatusPreservesDisabledActiveConflict 验证数据库已停用但实例仍连接时 HTTP 查询返回冲突诊断而非掩盖为 disabled。
|
||||
func TestCookieRuntimeStatusPreservesDisabledActiveConflict(t *testing.T) {
|
||||
// srv、store、cleanup 保存已认证 HTTP 夹具、持久化状态和资源清理函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// statusErr 保存将测试账号持久化状态切换为停用的错误。
|
||||
statusErr := store.Cookies.SetStatus(context.Background(), "acc1", false)
|
||||
if statusErr != nil {
|
||||
t.Fatalf("停用测试账号失败: %v", statusErr)
|
||||
}
|
||||
// runtimePort 模拟旧运行实例尚未退出时返回的连接中快照。
|
||||
runtimePort := runtimeStatusPortStub{statuses: map[string]accountapp.RuntimeStatus{
|
||||
"acc1": {State: "connecting", Message: "旧实例仍在关闭", Connected: true, UpdatedAt: time.Now().UTC()},
|
||||
}}
|
||||
srv.applications.accountRuntime = runtimePort
|
||||
// handler 是含认证中间件的 HTTP 路由。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 保存管理员认证会话 Cookie。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// request 是读取版本化运行状态的 HTTP 请求。
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/runtime-status", nil)
|
||||
request.AddCookie(sessionCookie)
|
||||
// recorder 捕获运行状态响应。
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("运行状态 HTTP status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
// statuses 保存解码后的按账号运行状态映射。
|
||||
statuses := map[string]accountapp.RuntimeStatus{}
|
||||
// decodeErr 保存 HTTP 响应不符合非敏感运行状态 DTO 时的 JSON 解码错误。
|
||||
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &statuses); decodeErr != nil {
|
||||
t.Fatalf("解析运行状态响应失败: %v", decodeErr)
|
||||
}
|
||||
// status 是冲突账号返回的运行时快照,必须保留实际连接状态。
|
||||
if status := statuses["acc1"]; status.State != "runtime_conflict" || !status.Connected {
|
||||
t.Fatalf("停用但存活的实例被掩盖: %+v", status)
|
||||
}
|
||||
}
|
||||
|
||||
// cachedAccountNickname 保留测试对账号展示名兼容规则的独立验证,不参与生产 HTTP 路径。
|
||||
func cachedAccountNickname(d *db.CookieDetail) string {
|
||||
if strings.TrimSpace(d.Remark) != "" {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
"xianyu-go/internal/auth"
|
||||
)
|
||||
|
||||
// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API;停用但仍存活的实例必须作为冲突诊断返回。
|
||||
func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前认证会话,只用于按用户过滤非敏感账号标识。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// accountSummary 提供账号归属、启用状态和非敏感 ID 查询。
|
||||
accountSummary := s.accountSummaryApplication()
|
||||
// cookieIDs、listErr 保存当前用户账号标识列表及读取错误。
|
||||
cookieIDs, listErr := accountSummary.ListOwnedIDs(r.Context(), sess.UserID)
|
||||
if listErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号失败")
|
||||
return
|
||||
}
|
||||
// runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。
|
||||
runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context())
|
||||
if runtimeErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败")
|
||||
return
|
||||
}
|
||||
// result 是按当前用户账号 ID 返回的非敏感运行状态映射。
|
||||
result := make(map[string]accountapp.RuntimeStatus, len(cookieIDs))
|
||||
// cid 是当前需要合并数据库启用状态和运行实例快照的账号标识。
|
||||
for _, cid := range cookieIDs {
|
||||
// enabled、statusErr 保存数据库启用状态及归属复核错误。
|
||||
enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid)
|
||||
if statusErr != nil {
|
||||
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
|
||||
continue
|
||||
}
|
||||
// status、ok 保存运行实例快照及其存在标记。
|
||||
if status, ok := runtime[cid]; ok {
|
||||
if !enabled && runtimeStatusIsActive(status) {
|
||||
status.State = "runtime_conflict"
|
||||
status.Message = "数据库已停用,但运行实例仍存活,请重试停用"
|
||||
result[cid] = status
|
||||
continue
|
||||
}
|
||||
result[cid] = status
|
||||
continue
|
||||
}
|
||||
if !enabled {
|
||||
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
|
||||
continue
|
||||
}
|
||||
result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// runtimeStatusIsActive 判断运行时快照是否代表仍需关注的活动实例;已退出的 error/stopped 不伪装成冲突。
|
||||
func runtimeStatusIsActive(status accountapp.RuntimeStatus) bool {
|
||||
if status.Connected {
|
||||
return true
|
||||
}
|
||||
switch status.State {
|
||||
case "starting", "connecting", "online", "reconnecting", "auth_expired", "verification_required":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
// cookieID、filterStatus 保存订单刷新筛选条件。
|
||||
cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status")
|
||||
// started、err 保存应用服务创建并启动任务的结果。
|
||||
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), r.Context(), sess.UserID, cookieID, filterStatus)
|
||||
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), sess.UserID, cookieID, filterStatus)
|
||||
if errors.Is(err, orderapp.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
|
||||
return
|
||||
|
||||
@@ -53,6 +53,27 @@ type testOrdersTransport struct {
|
||||
services *orderapp.ServiceSet
|
||||
}
|
||||
|
||||
// testOrderRefreshJobsTransport 将测试组合根订单刷新服务投影为 HTTP Port,并隔离请求 Context 与 worker 生命周期。
|
||||
type testOrderRefreshJobsTransport struct {
|
||||
// service 是测试组合根构造的订单刷新任务应用服务。
|
||||
service *orderapp.RefreshJobService
|
||||
}
|
||||
|
||||
// CreateAndStart 使用请求 Context 完成创建,并使用测试进程 Context 驱动后台 worker。
|
||||
func (transport testOrderRefreshJobsTransport) CreateAndStart(requestCtx context.Context, userID int64, cookieID, status string) (orderapp.RefreshJobStartResult, error) {
|
||||
return transport.service.CreateAndStart(requestCtx, context.Background(), userID, cookieID, status)
|
||||
}
|
||||
|
||||
// GetJob 返回当前用户拥有的订单刷新任务状态。
|
||||
func (transport testOrderRefreshJobsTransport) GetJob(ctx context.Context, userID int64, jobID string) (*orderapp.RefreshJob, error) {
|
||||
return transport.service.GetJob(ctx, userID, jobID)
|
||||
}
|
||||
|
||||
// CancelForUser 取消当前用户拥有的订单刷新任务。
|
||||
func (transport testOrderRefreshJobsTransport) CancelForUser(ctx context.Context, userID int64, jobID string) (orderapp.RefreshJobCancelResult, error) {
|
||||
return transport.service.CancelForUser(ctx, userID, jobID)
|
||||
}
|
||||
|
||||
// RefreshSingle 转发测试的单订单刷新用例。
|
||||
func (transport testOrdersTransport) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderapp.SingleRefreshResult, error) {
|
||||
return transport.services.Refresh.RefreshSingle(ctx, userID, orderID)
|
||||
|
||||
@@ -359,7 +359,7 @@ func testServerDependencies(authentication *auth.Service, databaseHealth Databas
|
||||
// ports 是测试组合根投影的完整 transport Port 集合。
|
||||
ports := services.TransportPorts()
|
||||
return Dependencies{Auth: authentication, Addr: ":0", DatabaseHealth: databaseHealth, Applications: NewApplicationPorts(ApplicationPortsInput{
|
||||
Orders: testOrdersTransport{services: ports.Orders}, OrderRefreshJobs: ports.OrderRefreshJobs, ItemSinglePublish: ports.ItemSinglePublish,
|
||||
Orders: testOrdersTransport{services: ports.Orders}, OrderRefreshJobs: testOrderRefreshJobsTransport{service: ports.OrderRefreshJobs}, ItemSinglePublish: ports.ItemSinglePublish,
|
||||
ItemBatchPreview: ports.ItemBatchPreview, ItemBatchManagement: ports.ItemBatchManagement, ItemCategoryRecommendation: ports.ItemCategoryRecommendation,
|
||||
ItemBatchPreviewPersistence: ports.ItemBatchPreviewPersistence, ItemBatchLocalPublish: ports.ItemBatchLocalPublish,
|
||||
ItemSync: ports.ItemSync, ItemCatalog: ports.ItemCatalog, ItemCatalogMutation: ports.ItemCatalogMutation,
|
||||
|
||||
Reference in new issue
Block a user