阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -1,22 +1,14 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
import "testing"
|
||||
|
||||
// TestServerCookieWriterRejectsMissingRepository 验证 Server 凭证写入适配器缺少 Port 时快速失败。
|
||||
// TestServerCookieWriterRejectsMissingRepository 验证 Server 缺少窄凭证端口时快速失败。
|
||||
func TestServerCookieWriterRejectsMissingRepository(t *testing.T) {
|
||||
// writer 模拟请求边界持有明文 Cookie 但尚未完成凭证 Port 装配的状态。
|
||||
writer := serverCookieWriter{cookies: "sid=short-lived"}
|
||||
// createErr 保存新增账号写入的装配错误。
|
||||
createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1)
|
||||
if createErr == nil {
|
||||
t.Fatal("缺少凭证 Port 时新增 Cookie 不应伪装成功")
|
||||
}
|
||||
// updateErr 保存既有账号更新的装配错误。
|
||||
updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 0)
|
||||
if updateErr == nil {
|
||||
t.Fatal("缺少凭证 Port 时更新 Cookie 不应伪装成功")
|
||||
// srv 模拟尚未完成账号应用服务装配的 Server。
|
||||
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
|
||||
// sessionPort 保存缺少凭证仓储时的会话写回端口。
|
||||
sessionPort := srv.platformCredentialSessionPort()
|
||||
if sessionPort != nil {
|
||||
t.Fatal("缺少凭证 Port 时 Server 不应暴露伪造的会话端口")
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/adapter"
|
||||
@@ -14,99 +12,23 @@ import (
|
||||
|
||||
// accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。
|
||||
type accountLoginService struct {
|
||||
// server 提供账号存储、运行时管理器和扫码会话持久化依赖。
|
||||
server *Server
|
||||
// repository 提供账号登录服务所需的最小凭证持久化能力。
|
||||
repository accountapp.CredentialRepository
|
||||
// summaryRepository 提供不解密凭证的账号摘要和归属查询能力。
|
||||
summaryRepository accountapp.AccountSummaryRepository
|
||||
// cookieWriterFactory 按请求创建新增 Cookie 写入端口;明文只进入返回的短生命周期实例。
|
||||
cookieWriterFactory func(string) accountapp.CookieWriter
|
||||
// cookieUpdaterFactory 按请求创建既有 Cookie 更新端口;明文只进入返回的短生命周期实例。
|
||||
cookieUpdaterFactory func(string) accountapp.CookieUpdater
|
||||
// sessionPort 提供平台会话写回所需的最小凭证能力,不暴露完整账号仓储。
|
||||
sessionPort accountapp.CredentialSessionPort
|
||||
// createApplication 提供已迁移的手动 Cookie 登录应用用例。
|
||||
createApplication *accountapp.LoginService
|
||||
// qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。
|
||||
// qrApplication 提供扫码成功凭证持久化应用用例。
|
||||
qrApplication *accountapp.QRLoginService
|
||||
// qrSessions 持有扫码会话所有权和幂等结果,Server 只负责 HTTP 适配。
|
||||
qrSessions *accountapp.QRLoginSessionRegistry
|
||||
}
|
||||
|
||||
// serverLoginLifecyclePort 将登录成功后的审计、资料刷新和运行时重启适配到应用层端口。
|
||||
type serverLoginLifecyclePort struct {
|
||||
// server 提供现有 Server 运行时与审计适配能力。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// AfterSuccessfulLogin 在凭证写入并释放凭证锁后执行 Server 侧登录后续编排。
|
||||
func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID, method string) {
|
||||
if p.server == nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(method) != "" {
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
|
||||
}
|
||||
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
|
||||
}
|
||||
|
||||
// serverCookieWriter 将本次请求中的明文 Cookie 限制在 Server 基础设施适配器内。
|
||||
type serverCookieWriter struct {
|
||||
// repository 提供凭证锁、写入和旧 Token 清理能力。
|
||||
repository accountapp.CredentialRepository
|
||||
// cookies 保存当前请求明文 Cookie;仅在 CreateOwnedCookie 调用期间使用,不进入应用层模型。
|
||||
cookies string
|
||||
// logger 提供旧 Token 清理失败的脱敏日志能力。
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// CreateOwnedCookie 在凭证锁内原子校验归属、写入 Cookie 并清理旧连接 Token。
|
||||
func (w serverCookieWriter) CreateOwnedCookie(ctx context.Context, accountID string, userID int64) error {
|
||||
if w.repository == nil {
|
||||
return errors.New("账号登录凭证 repository 未初始化")
|
||||
}
|
||||
// unlock 保护凭证写入与旧连接 Token 清理,外部网络和运行时操作在锁外执行。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// writeErr 保存凭证写入错误;归属校验失败时直接返回且不清理 Token。
|
||||
writeErr := w.repository.CreateCookieOwned(ctx, accountID, w.cookies, userID)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;清理失败不回滚已经成功写入的 Cookie。
|
||||
clearErr := w.repository.ClearTokens(ctx, accountID)
|
||||
if clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、Cookie 写入和旧 Token 清理;慢速资料刷新由应用服务在解锁后触发。
|
||||
func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error {
|
||||
if w.repository == nil {
|
||||
return errors.New("账号登录凭证 repository 未初始化")
|
||||
}
|
||||
// unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时操作。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。
|
||||
detail, loadErr := w.repository.LoadPlatformDetail(ctx, accountID)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
if detail == nil || detail.UserID != userID {
|
||||
return accountapp.ErrForbidden
|
||||
}
|
||||
if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision {
|
||||
return accountapp.ErrCredentialConflict
|
||||
}
|
||||
// updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。
|
||||
if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。
|
||||
if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其 Server 生命周期适配器。
|
||||
func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, error) {
|
||||
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
|
||||
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其生命周期适配器。
|
||||
func newAccountLoginCreateApplication(lifecycle accountapp.LoginLifecyclePort) (*accountapp.LoginService, error) {
|
||||
return accountapp.NewLoginService(lifecycle)
|
||||
}
|
||||
|
||||
// accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。
|
||||
@@ -114,9 +36,13 @@ func (s *Server) accountLoginApplication() *accountLoginService {
|
||||
return s.applicationServiceSet().accountLogin
|
||||
}
|
||||
|
||||
// accountLoginRepositoryForServer 返回当前 Server 装配的账号登录持久化边界。
|
||||
func (s *Server) accountLoginRepositoryForServer() accountapp.CredentialRepository {
|
||||
return s.accountLoginApplication().repository
|
||||
// platformCredentialSessionPort 返回平台 Cookie 会话写回所需的最小应用端口。
|
||||
// Server 不通过该端口读取账号或登录秘密;凭证锁仍由调用方在慢速平台 I/O 之外管理。
|
||||
func (s *Server) platformCredentialSessionPort() accountapp.CredentialSessionPort {
|
||||
if s == nil || s.accountLoginApplication() == nil {
|
||||
return nil
|
||||
}
|
||||
return s.accountLoginApplication().sessionPort
|
||||
}
|
||||
|
||||
// accountLoginInput 是新增账号登录凭证用例的业务输入。
|
||||
@@ -147,132 +73,74 @@ type accountCookieUpdateInput struct {
|
||||
|
||||
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountLoginInput) error {
|
||||
if svc == nil || svc.createApplication == nil || svc.server == nil {
|
||||
if svc == nil || svc.createApplication == nil {
|
||||
return errors.New("账号登录应用服务未初始化")
|
||||
}
|
||||
if svc.cookieWriterFactory == nil {
|
||||
return errors.New("账号 Cookie 写入端口未初始化")
|
||||
}
|
||||
return svc.createApplication.CreateCookie(ctx, accountapp.CreateCookieInput{
|
||||
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod,
|
||||
}, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger})
|
||||
}, svc.cookieWriterFactory(input.Cookies))
|
||||
}
|
||||
|
||||
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error {
|
||||
if svc == nil || svc.createApplication == nil || svc.server == nil {
|
||||
if svc == nil || svc.createApplication == nil {
|
||||
return errors.New("账号登录应用服务未初始化")
|
||||
}
|
||||
if svc.cookieUpdaterFactory == nil {
|
||||
return errors.New("账号 Cookie 更新端口未初始化")
|
||||
}
|
||||
return svc.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{
|
||||
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, ExpectedRevision: input.ExpectedRevision,
|
||||
}, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger})
|
||||
}
|
||||
|
||||
// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。
|
||||
type serverQRLoginLifecycle struct {
|
||||
// server 提供审计、资料刷新、自动化唤醒和账号运行时管理能力。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// AfterSuccessfulQRLogin 在凭证锁释放后执行扫码登录成功的后续编排。
|
||||
func (p serverQRLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) {
|
||||
if p.server == nil {
|
||||
return
|
||||
}
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
|
||||
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
|
||||
p.server.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
}
|
||||
|
||||
// ReportQRLoginCleanupFailure 记录扫码登录后旧 Token 清理失败,不暴露 Cookie 内容且不回滚已写入凭证。
|
||||
func (p serverQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) {
|
||||
if p.server != nil && p.server.Logger != nil {
|
||||
p.server.Logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}, svc.cookieUpdaterFactory(input.Cookies))
|
||||
}
|
||||
|
||||
// PersistQRLoginSuccess 将 HTTP/平台 map 适配为纯应用 DTO,并复用会话级幂等锁。
|
||||
func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
if svc == nil || svc.server == nil || svc.qrApplication == nil {
|
||||
if svc == nil || svc.qrApplication == nil || svc.qrSessions == nil {
|
||||
return qrLoginPersistence{}, errors.New("扫码登录应用服务未初始化")
|
||||
}
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// lockValue 和 persistMu 保证同一扫码会话只执行一次持久化。
|
||||
lockValue, _ := s.qrPersistLocks.LoadOrStore(sessionID, &sync.Mutex{})
|
||||
// persistMu 是当前扫码会话的串行化锁。
|
||||
persistMu := lockValue.(*sync.Mutex)
|
||||
persistMu.Lock()
|
||||
defer persistMu.Unlock()
|
||||
|
||||
s.qrMu.Lock()
|
||||
if s.qrPersisted == nil {
|
||||
s.qrPersisted = make(map[string]qrLoginPersistence)
|
||||
}
|
||||
// persisted 和 ok 保存已完成的幂等结果及其存在性。
|
||||
if persisted, ok := s.qrPersisted[sessionID]; ok {
|
||||
s.qrMu.Unlock()
|
||||
if persisted.UserID != userID {
|
||||
return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户")
|
||||
// persisted 保存注册表执行凭证持久化后返回的非敏感幂等结果。
|
||||
persisted, persistErr := svc.qrSessions.PersistOnce(sessionID, userID, func() (accountapp.QRLoginSessionPersistence, error) {
|
||||
// cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。
|
||||
cookies := qrString(result, "cookies")
|
||||
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。
|
||||
cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result)
|
||||
// scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。
|
||||
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), adapter.AccountIDFromCookie(cookies)))
|
||||
// input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。
|
||||
input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies}
|
||||
if snapshotComplete {
|
||||
input.Snapshot = cookieSnapshot
|
||||
}
|
||||
return persisted, nil
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
// cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。
|
||||
cookies := qrString(result, "cookies")
|
||||
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。
|
||||
cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result)
|
||||
// scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。
|
||||
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), adapter.AccountIDFromCookie(cookies)))
|
||||
// input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。
|
||||
input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies}
|
||||
if snapshotComplete {
|
||||
input.Snapshot = cookieSnapshot
|
||||
}
|
||||
// resultValue 保存应用服务返回的非敏感持久化结果。
|
||||
resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input)
|
||||
// resultValue 保存应用服务返回的非敏感持久化结果。
|
||||
resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input)
|
||||
if persistErr != nil {
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) {
|
||||
return accountapp.QRLoginSessionPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) {
|
||||
return accountapp.QRLoginSessionPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrForbidden) {
|
||||
return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrAlreadyExists) {
|
||||
return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
|
||||
}
|
||||
return accountapp.QRLoginSessionPersistence{}, persistErr
|
||||
}
|
||||
return accountapp.QRLoginSessionPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, CreatedAt: time.Now().UTC()}, nil
|
||||
})
|
||||
if persistErr != nil {
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) {
|
||||
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) {
|
||||
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrForbidden) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrAlreadyExists) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginSessionForbidden) {
|
||||
return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户")
|
||||
}
|
||||
return qrLoginPersistence{}, persistErr
|
||||
}
|
||||
// persisted 是扫码会话幂等返回值。
|
||||
persisted := qrLoginPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, UserID: userID, CreatedAt: time.Now().UTC()}
|
||||
s.qrMu.Lock()
|
||||
s.qrPersisted[sessionID] = persisted
|
||||
s.qrMu.Unlock()
|
||||
s.qrPersistLocks.Delete(sessionID)
|
||||
return persisted, nil
|
||||
}
|
||||
|
||||
// refreshAndRestartAccount 在凭证锁释放后刷新资料并按账号状态重启运行时。
|
||||
func (svc *accountLoginService) refreshAndRestartAccount(ctx context.Context, userID int64, accountID string) {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// detail 和 err 保存资料摘要查询结果。
|
||||
_, err := svc.summaryRepository.GetOwnedSummary(ctx, userID, accountID)
|
||||
if err == nil {
|
||||
// profileResult、profileErr 保存登录成功后的资料刷新结果;失败仅记录,不阻断运行时重启。
|
||||
profileResult, profileErr := s.accountProfileApplication().RefreshProfile(ctx, userID, accountID)
|
||||
if profileErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("登录后刷新账号资料失败", "cookie_id", accountID, "err", profileErr)
|
||||
} else if profileResult.ErrorMessage != "" && s.Logger != nil {
|
||||
s.Logger.Warn("登录后刷新账号资料返回业务错误", "cookie_id", accountID, "err", profileResult.ErrorMessage)
|
||||
}
|
||||
}
|
||||
if s.Manager != nil && svc.repository.GetStatus(ctx, accountID) {
|
||||
// err 表示账号运行时重启错误。
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("账号登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
return qrLoginPersistence{AccountID: persisted.AccountID, IsNew: persisted.IsNew, UserID: persisted.UserID, CreatedAt: persisted.CreatedAt}, nil
|
||||
}
|
||||
|
||||
// ValidateCookieInput 校验账号标识和 Cookie 输入,供 HTTP 适配层复用一致规则。
|
||||
|
||||
@@ -48,15 +48,6 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// 不允许删除自己;应用服务统一执行该业务规则。
|
||||
sess := authSess(r)
|
||||
if s.Manager != nil {
|
||||
// accountIDs、listErr 保存应用服务返回的待停止账号 ID 列表及查询错误。
|
||||
if accountIDs, listErr := s.accountSummaryApplication().ListOwnedIDs(r.Context(), uid); listErr == nil {
|
||||
// cookieID 表示待停止运行实例的账号标识。
|
||||
for _, cookieID := range accountIDs {
|
||||
s.Manager.Stop(cookieID)
|
||||
}
|
||||
}
|
||||
}
|
||||
// err 保存管理员删除应用用例的执行结果。
|
||||
if err := s.applicationServiceSet().admin.DeleteUser(r.Context(), sess.UserID, uid); err != nil {
|
||||
if errors.Is(err, adminapp.ErrSelfDelete) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
keywordsapp "xianyu-go/internal/application/keywords"
|
||||
lifecycleapp "xianyu-go/internal/application/lifecycle"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
settingsapp "xianyu-go/internal/application/settings"
|
||||
@@ -20,14 +21,18 @@ import (
|
||||
|
||||
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
|
||||
type applicationServices struct {
|
||||
// platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。
|
||||
platformCredentials *accountapp.PlatformCredentialService
|
||||
// orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。
|
||||
orders *orderHTTPAdapter
|
||||
// orderRefreshJobs 是订单刷新任务创建、取消、恢复和 worker 生命周期应用服务。
|
||||
orderRefreshJobs *orderapp.RefreshJobService
|
||||
// orderReconciliationRecovery 是订单补偿扫描器的应用层生命周期协调器。
|
||||
orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
|
||||
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
|
||||
itemSinglePublish *itemapp.Service
|
||||
// itemBatchRunner 是商品批量发布 worker 的应用层编排器。
|
||||
itemBatchRunner *itemapp.BatchRunner
|
||||
// itemBatchRecovery 是过期批量发布任务的租约接管应用服务。
|
||||
itemBatchRecovery *itemapp.BatchRecoveryService
|
||||
// itemBatchCoordinator 是商品批量发布 worker、恢复扫描和关闭等待的生命周期拥有者。
|
||||
itemBatchCoordinator *itemapp.BatchWorkerCoordinator
|
||||
// itemBatchPreview 是商品批量发布表格预检应用服务。
|
||||
itemBatchPreview *itemapp.BatchPreviewService
|
||||
// itemBatchManagement 是商品批次查询、取消和重试应用服务。
|
||||
@@ -60,6 +65,8 @@ type applicationServices struct {
|
||||
accountLongLogin *accountapp.LongLoginService
|
||||
// accountSettings 是账号设置、登录信息、启停和暂停应用服务。
|
||||
accountSettings *accountapp.SettingsService
|
||||
// accountRuntime 是账号凭证写回后的运行时同步与状态快照应用服务。
|
||||
accountRuntime *accountapp.RuntimeService
|
||||
// accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。
|
||||
accountSummaries *accountapp.SummaryService
|
||||
// accountTasks 是账号任务设置、历史和手动执行应用服务。
|
||||
@@ -92,28 +99,122 @@ type applicationServices struct {
|
||||
admin *adminapp.Service
|
||||
}
|
||||
|
||||
// ApplicationLifecycleComponents 返回 Server 装配的应用 worker 生命周期组件。
|
||||
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
|
||||
func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent {
|
||||
if s == nil || s.applications == nil {
|
||||
return nil
|
||||
}
|
||||
// components 保存按应用依赖登记的 worker 生命周期组件。
|
||||
components := make([]lifecycleapp.NamedComponent, 0, 3)
|
||||
if s.applications.orderRefreshJobs != nil {
|
||||
// service 保存订单刷新恢复与 worker 生命周期应用服务。
|
||||
service := s.applications.orderRefreshJobs
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "order-refresh-recovery",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: service.StartRecovery,
|
||||
CloseFunc: service.Close,
|
||||
},
|
||||
})
|
||||
}
|
||||
if s.applications.itemBatchCoordinator != nil {
|
||||
// coordinator 保存批量发布 worker 与恢复扫描生命周期协调器。
|
||||
coordinator := s.applications.itemBatchCoordinator
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "publish-batch-workers",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: coordinator.StartRecovery,
|
||||
CloseFunc: coordinator.Close,
|
||||
},
|
||||
})
|
||||
}
|
||||
if s.applications.orderReconciliationRecovery != nil {
|
||||
// coordinator 保存订单补偿扫描生命周期协调器。
|
||||
coordinator := s.applications.orderReconciliationRecovery
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "order-reconciliation-recovery",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
StartFunc: coordinator.Start,
|
||||
CloseFunc: coordinator.Close,
|
||||
},
|
||||
})
|
||||
}
|
||||
return components
|
||||
}
|
||||
|
||||
// newApplicationServices 为指定 Server 装配全部应用服务实例。
|
||||
func newApplicationServices(server *Server) *applicationServices {
|
||||
// orderRepository 保存订单应用服务共享的基础设施适配器。
|
||||
orderRepository := server.dependencies.NewOrderRepository()
|
||||
orderRepository := server.orderDependencies.NewOrderRepository()
|
||||
// orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。
|
||||
orderReconciliation := server.dependencies.NewOrderReconciliationRepository()
|
||||
orderReconciliation := server.orderDependencies.NewOrderReconciliationRepository()
|
||||
// orderRuntime 保存订单服务共享的运行时能力适配器。
|
||||
orderRuntime := newServerOrderRuntime(server, orderReconciliation)
|
||||
// orderReconciliationRecovery 将补偿扫描器的启动、取消和等待收口到订单应用边界。
|
||||
orderReconciliationRecovery, orderReconciliationRecoveryErr := orderapp.NewReconciliationRecoveryCoordinator(server.systemDependencies.NewReconciliationService(server.Logger))
|
||||
if orderReconciliationRecoveryErr != nil {
|
||||
panic(orderReconciliationRecoveryErr)
|
||||
}
|
||||
// orderServices 保存应用层统一构造的订单业务服务集合。
|
||||
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.dependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
|
||||
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.orderDependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
|
||||
// orderRefreshRunner 是订单刷新后台 worker 与恢复扫描的生命周期拥有者。
|
||||
orderRefreshRunner, orderRefreshRunnerErr := orderapp.NewRefreshJobRunner(
|
||||
orderServices.RefreshJobs,
|
||||
orderServices.Refresh,
|
||||
orderapp.RefreshJobRunnerOptions{
|
||||
OnWorkerError: func(jobID string, err error) {
|
||||
if server.Logger != nil {
|
||||
server.Logger.Warn("订单刷新后台任务结束", "job_id", jobID, "err", err)
|
||||
}
|
||||
},
|
||||
OnRecoveryError: func(err error) {
|
||||
if server.Logger != nil {
|
||||
server.Logger.Warn("扫描订单刷新恢复任务失败", "err", err)
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
if orderRefreshRunnerErr != nil {
|
||||
panic(orderRefreshRunnerErr)
|
||||
}
|
||||
// orderRefreshJobs 是订单刷新任务应用 facade,封装归属、租约和 worker 启动编排。
|
||||
orderRefreshJobs, orderRefreshJobsErr := orderapp.NewRefreshJobService(
|
||||
orderServices.RefreshJobs,
|
||||
orderServices.Refresh,
|
||||
orderRefreshRunner,
|
||||
orderapp.RefreshJobServiceOptions{},
|
||||
)
|
||||
if orderRefreshJobsErr != nil {
|
||||
panic(orderRefreshJobsErr)
|
||||
}
|
||||
// accountProfile 保存账号资料刷新用例的构造结果。
|
||||
// accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。
|
||||
accountRepository := server.dependencies.NewAccountLoginRepository()
|
||||
accountRepository := server.accountDependencies.NewAccountLoginRepository()
|
||||
// platformCredentials 将账号凭证读取限制在消费者定义的只读应用端口。
|
||||
platformCredentials, platformCredentialsErr := accountapp.NewPlatformCredentialService(accountRepository)
|
||||
if platformCredentialsErr != nil {
|
||||
panic(platformCredentialsErr)
|
||||
}
|
||||
// cookieWriterFactory 将明文 Cookie 封装在 adapter 的请求范围实例中,Server 不持有凭证仓储。
|
||||
cookieWriterFactory := func(cookies string) accountapp.CookieWriter {
|
||||
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger)
|
||||
}
|
||||
// cookieUpdaterFactory 将既有账号的明文 Cookie 封装在 adapter 的请求范围实例中。
|
||||
cookieUpdaterFactory := func(cookies string) accountapp.CookieUpdater {
|
||||
return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger)
|
||||
}
|
||||
// sessionRecovery 统一适配平台 Session 失效分类、诊断日志和账号运行时恢复。
|
||||
sessionRecovery := server.sessionRecoveryCallback()
|
||||
// accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。
|
||||
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, server.recoverExpiredMTOPSession, server.Logger))
|
||||
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, sessionRecovery, server.Logger))
|
||||
if profileErr != nil {
|
||||
panic(profileErr)
|
||||
}
|
||||
// accountLongLogin 由适配器承载平台调用、Cookie 快照合并和凭证写回。
|
||||
accountLongLogin, longLoginErr := accountapp.NewLongLoginService(
|
||||
accountRepository,
|
||||
adapter.NewLongLoginAdapter(accountRepository, func() adapter.LongLoginClient { return server.CookieRenew }, server.updateRunningCookie, server.Logger),
|
||||
adapter.NewLongLoginAdapter(accountRepository, server.longLoginClient, server.updateRunningCookie, server.Logger),
|
||||
)
|
||||
if longLoginErr != nil {
|
||||
panic(longLoginErr)
|
||||
@@ -124,22 +225,40 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
settingsRuntime = server.Manager
|
||||
}
|
||||
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
|
||||
accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.dependencies.NewAccountSettingsRepository(), settingsRuntime)
|
||||
accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.accountDependencies.NewAccountSettingsRepository(), settingsRuntime)
|
||||
if accountSettingsErr != nil {
|
||||
panic(accountSettingsErr)
|
||||
}
|
||||
// accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。
|
||||
accountSummaryRepository := server.dependencies.NewAccountSummaryRepository()
|
||||
accountSummaryRepository := server.accountDependencies.NewAccountSummaryRepository()
|
||||
// accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。
|
||||
accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository)
|
||||
if accountSummariesErr != nil {
|
||||
panic(accountSummariesErr)
|
||||
}
|
||||
// credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。
|
||||
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(server.dependencies.NewAutomationCredentialWakeRepository())
|
||||
// automationDependencies 提供自动化、默认回复和关键词用例的显式适配器工厂。
|
||||
automationDependencies := server.automationDependencies
|
||||
if automationDependencies == nil {
|
||||
panic("自动化专用依赖未装配")
|
||||
}
|
||||
// credentialWake、credentialWakeErr 保存凭证恢复后的自动化唤醒应用服务及装配错误。
|
||||
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(automationDependencies.NewAutomationCredentialWakeRepository())
|
||||
if credentialWakeErr != nil {
|
||||
panic(credentialWakeErr)
|
||||
}
|
||||
// accountRuntime 将 Manager 与凭证恢复后的自动化唤醒收口到账号应用端口。
|
||||
accountRuntime := accountapp.NewRuntimeService(adapter.NewAccountRuntimePort(server.Manager), credentialWake)
|
||||
// loginSuccess 负责登录成功后的资料刷新和启用账号运行时重启,避免 Server 持有业务编排。
|
||||
loginSuccess := accountapp.NewLoginSuccessService(accountRepository, accountProfile, accountRepository, accountRuntime, func(message string, err error) {
|
||||
if server.Logger != nil {
|
||||
server.Logger.Warn(message, "err", err)
|
||||
}
|
||||
})
|
||||
// loginAudit 负责登录方式、账号启用和审计日志写入,生命周期适配器只组合应用端口。
|
||||
loginAudit := accountapp.NewLoginAuditService(server.accountDependencies.NewAccountLoginAuditRepository())
|
||||
// loginLifecycle 将手动登录与扫码登录的成功后续动作收口到 adapter,不再反向持有 Server。
|
||||
loginLifecycle := adapter.NewAccountLoginLifecycle(loginAudit, loginSuccess, server.Logger)
|
||||
// deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。
|
||||
var deleteRuntime accountapp.DeleteRuntime
|
||||
if server.Manager != nil {
|
||||
@@ -151,14 +270,16 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
panic(deleteErr)
|
||||
}
|
||||
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
|
||||
itemBatchPublish := server.dependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
server.recoverExpiredMTOPSession(ctx, cookieID, err)
|
||||
itemBatchPublish := server.itemDependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
}, readBatchImageFile, downloadImageURL)
|
||||
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
|
||||
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
|
||||
server.dependencies.NewItemBatchRepository(),
|
||||
server.dependencies.NewItemCatalogRepository(),
|
||||
server.dependencies.NewAutomationRepository(),
|
||||
server.itemDependencies.NewItemBatchRepository(),
|
||||
server.itemDependencies.NewItemCatalogRepository(),
|
||||
automationDependencies.NewAutomationRepository(),
|
||||
)
|
||||
if itemBatchLocalPublishErr != nil {
|
||||
panic(itemBatchLocalPublishErr)
|
||||
@@ -168,54 +289,72 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
if batchRunnerErr != nil {
|
||||
panic(batchRunnerErr)
|
||||
}
|
||||
// itemBatchRecovery 负责恢复扫描的批次状态编排,worker 启动仍由 Server 生命周期边界提供。
|
||||
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
|
||||
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
|
||||
server.dependencies.NewItemBatchRepository(),
|
||||
itemapp.BatchRecoveryOptions{
|
||||
LeaseDuration: publishBatchLease,
|
||||
StartWorker: func(ctx context.Context, userID int64, batchID, workerToken string) {
|
||||
server.startPublishBatchWorker(ctx, userID, batchID, workerToken)
|
||||
},
|
||||
},
|
||||
server.itemDependencies.NewItemBatchRepository(),
|
||||
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
|
||||
)
|
||||
if batchRecoveryErr != nil {
|
||||
panic(batchRecoveryErr)
|
||||
}
|
||||
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
|
||||
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
|
||||
OnWorkerError: func(batchID string, err error) {
|
||||
if server.Logger != nil {
|
||||
server.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err)
|
||||
}
|
||||
},
|
||||
OnRecoveryError: func(err error) {
|
||||
if server.Logger != nil {
|
||||
server.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
|
||||
}
|
||||
},
|
||||
})
|
||||
if batchCoordinatorErr != nil {
|
||||
panic(batchCoordinatorErr)
|
||||
}
|
||||
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
|
||||
itemBatchPreviewPort := server.dependencies.NewItemBatchPreviewPort()
|
||||
itemBatchPreviewPort := server.itemDependencies.NewItemBatchPreviewPort()
|
||||
// itemBatchPreview 是批量发布预检应用服务的构造结果。
|
||||
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
|
||||
if itemBatchPreviewErr != nil {
|
||||
panic(itemBatchPreviewErr)
|
||||
}
|
||||
// itemBatchManagement 是批次管理应用服务的构造结果。
|
||||
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.dependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server})
|
||||
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.itemDependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server, coordinator: itemBatchCoordinator})
|
||||
if itemBatchManagementErr != nil {
|
||||
panic(itemBatchManagementErr)
|
||||
}
|
||||
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
|
||||
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(server)
|
||||
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(loginLifecycle)
|
||||
if accountLoginCreateErr != nil {
|
||||
panic(accountLoginCreateErr)
|
||||
}
|
||||
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
|
||||
var accountQRLogin *accountapp.QRLoginService
|
||||
if server.dependencies != nil {
|
||||
if server.accountDependencies != nil {
|
||||
// accountQRLoginErr 保存扫码应用服务装配失败原因。
|
||||
var accountQRLoginErr error
|
||||
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.dependencies.NewQRLoginRepository(), serverQRLoginLifecycle{server: server})
|
||||
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.accountDependencies.NewQRLoginRepository(), loginLifecycle)
|
||||
if accountQRLoginErr != nil {
|
||||
panic(accountQRLoginErr)
|
||||
}
|
||||
}
|
||||
// qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。
|
||||
qrSessionRegistry := accountapp.NewQRLoginSessionRegistry()
|
||||
// automationRepository 复用同一个数据库适配器,保持自动化异常与规则查询的基础设施边界一致。
|
||||
automationRepository := server.dependencies.NewAutomationRepository()
|
||||
automationRepository := automationDependencies.NewAutomationRepository()
|
||||
// settingsService 统一装配设置数据库与远端模型目录适配器。
|
||||
settingsService := settingsapp.NewService(server.dependencies.NewSettingsRepository(), adapter.NewAIModelClient())
|
||||
// adminService 负责管理员用户与仪表盘查询,HTTP 层只做 DTO 映射。
|
||||
adminService := adminapp.NewService(server.dependencies.NewAdminRepository())
|
||||
settingsService := settingsapp.NewService(server.adminSettingsDependencies.NewSettingsRepository(), adapter.NewAIModelClient())
|
||||
// adminRuntime 是管理员删除用户前收束账号运行实例的窄端口;无 Manager 的离线测试保持为空。
|
||||
var adminRuntime adminapp.Runtime
|
||||
if server.Manager != nil {
|
||||
adminRuntime = server.Manager
|
||||
}
|
||||
// adminService 负责管理员用户与仪表盘查询及删除前的账号运行时收束,HTTP 层只做 DTO 映射。
|
||||
adminService := adminapp.NewServiceWithRuntime(server.adminSettingsDependencies.NewAdminRepository(), adminRuntime)
|
||||
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
|
||||
itemCatalogRepository := server.dependencies.NewItemCatalogRepository()
|
||||
itemCatalogRepository := server.itemDependencies.NewItemCatalogRepository()
|
||||
// itemCatalog 是商品列表和详情读取用例的应用服务。
|
||||
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
|
||||
if itemCatalogErr != nil {
|
||||
@@ -227,8 +366,10 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
panic(itemCatalogMutationErr)
|
||||
}
|
||||
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
|
||||
itemPublishPort := server.dependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
server.recoverExpiredMTOPSession(ctx, cookieID, err)
|
||||
itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
})
|
||||
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
|
||||
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
|
||||
@@ -236,69 +377,84 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
panic(itemCategoryRecommendationErr)
|
||||
}
|
||||
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
|
||||
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.dependencies.NewItemBatchRepository())
|
||||
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.itemDependencies.NewItemBatchRepository())
|
||||
if itemBatchPreviewPersistenceErr != nil {
|
||||
panic(itemBatchPreviewPersistenceErr)
|
||||
}
|
||||
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
|
||||
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
|
||||
itemPublishPort,
|
||||
server.dependencies.NewItemPublishRepository(),
|
||||
server.itemDependencies.NewItemPublishRepository(),
|
||||
)
|
||||
if itemSinglePublishErr != nil {
|
||||
panic(itemSinglePublishErr)
|
||||
}
|
||||
return &applicationServices{
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
platformCredentials: platformCredentials,
|
||||
orders: &orderHTTPAdapter{services: orderServices},
|
||||
orderRefreshJobs: orderRefreshJobs,
|
||||
orderReconciliationRecovery: orderReconciliationRecovery,
|
||||
itemSinglePublish: itemSinglePublish,
|
||||
itemBatchRunner: itemBatchRunner,
|
||||
itemBatchRecovery: itemBatchRecovery,
|
||||
itemBatchCoordinator: itemBatchCoordinator,
|
||||
itemBatchPreview: itemBatchPreview,
|
||||
itemBatchManagement: itemBatchManagement,
|
||||
itemCategoryRecommendation: itemCategoryRecommendation,
|
||||
itemBatchPreviewPersistence: itemBatchPreviewPersistence,
|
||||
itemBatchLocalPublish: itemBatchLocalPublish,
|
||||
itemSync: itemapp.NewSyncService(server.dependencies.NewItemSyncRepository(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
server.recoverExpiredMTOPSession(ctx, cookieID, err)
|
||||
itemSync: itemapp.NewSyncService(server.itemDependencies.NewItemSyncRepository(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
})),
|
||||
itemCatalog: itemCatalog,
|
||||
itemCatalogMutation: itemCatalogMutation,
|
||||
accountLogin: &accountLoginService{server: server, repository: accountRepository, summaryRepository: accountSummaryRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin},
|
||||
accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry},
|
||||
authentication: newAuthenticationApplication(server),
|
||||
loginAudit: accountapp.NewLoginAuditService(server.dependencies.NewAccountLoginAuditRepository()),
|
||||
loginAudit: loginAudit,
|
||||
passwordLogin: accountapp.NewPasswordLoginService(),
|
||||
accountDelete: accountDelete,
|
||||
accountProfile: accountProfile,
|
||||
accountLongLogin: accountLongLogin,
|
||||
accountSettings: accountSettings,
|
||||
accountRuntime: accountRuntime,
|
||||
accountSummaries: accountSummaries,
|
||||
accountTasks: automationapp.NewService(server.dependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)),
|
||||
accountTasks: automationapp.NewService(automationDependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)),
|
||||
credentialWake: credentialWake,
|
||||
chat: newChatSendingApplication(server),
|
||||
uncertainNotifications: notificationsapp.New(server.dependencies.NewNotificationUncertainRepository()),
|
||||
notificationChannels: notificationsapp.NewChannelService(server.dependencies.NewNotificationChannelRepository(), server.notifier),
|
||||
analytics: analyticsapp.NewService(server.dependencies.NewAnalyticsRepository()),
|
||||
uncertainNotifications: notificationsapp.New(server.miscDependencies.NewNotificationUncertainRepository()),
|
||||
notificationChannels: notificationsapp.NewChannelService(server.miscDependencies.NewNotificationChannelRepository(), server.notifier),
|
||||
analytics: analyticsapp.NewService(server.miscDependencies.NewAnalyticsRepository()),
|
||||
automationRules: automationapp.NewRuleService(automationRepository, automationRepository),
|
||||
cards: cardsapp.NewService(server.dependencies.NewCardsRepository()),
|
||||
cards: cardsapp.NewService(server.miscDependencies.NewCardsRepository()),
|
||||
publishAutomationRules: automationapp.NewPublishRuleService(automationRepository),
|
||||
automationIssues: automationapp.NewIssueService(automationRepository),
|
||||
defaultReplies: defaultreplyapp.NewService(server.dependencies.NewDefaultReplyRepository()),
|
||||
keywords: keywordsapp.NewService(server.dependencies.NewKeywordRepository()),
|
||||
defaultReplies: defaultreplyapp.NewService(automationDependencies.NewDefaultReplyRepository()),
|
||||
keywords: keywordsapp.NewService(automationDependencies.NewKeywordRepository()),
|
||||
settings: settingsService,
|
||||
admin: adminService,
|
||||
}
|
||||
}
|
||||
|
||||
// accountRuntimeApplication 返回当前 Server 绑定的账号运行时应用服务。
|
||||
func (s *Server) accountRuntimeApplication() *accountapp.RuntimeService {
|
||||
return s.applicationServiceSet().accountRuntime
|
||||
}
|
||||
|
||||
// newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。
|
||||
func newAuthenticationApplication(server *Server) *accountapp.AuthenticationService {
|
||||
// authentication、authenticationErr 保存认证应用服务及其装配错误。
|
||||
authentication, authenticationErr := accountapp.NewAuthenticationService(server.dependencies.NewAuthenticationRepository())
|
||||
authentication, authenticationErr := accountapp.NewAuthenticationService(server.accountDependencies.NewAuthenticationRepository())
|
||||
if authenticationErr != nil {
|
||||
panic(authenticationErr)
|
||||
}
|
||||
return authentication
|
||||
}
|
||||
|
||||
// orderRefreshJobsApplication 返回当前 Server 绑定的订单刷新任务应用服务。
|
||||
func (s *Server) orderRefreshJobsApplication() *orderapp.RefreshJobService {
|
||||
return s.applicationServiceSet().orderRefreshJobs
|
||||
}
|
||||
|
||||
// itemCatalogApplication 返回当前 Server 绑定的商品读取应用服务。
|
||||
func (s *Server) itemCatalogApplication() *itemapp.CatalogService {
|
||||
return s.applicationServiceSet().itemCatalog
|
||||
@@ -329,11 +485,6 @@ func (s *Server) accountTaskApplication() *automationapp.Service {
|
||||
return s.applicationServiceSet().accountTasks
|
||||
}
|
||||
|
||||
// credentialWakeApplication 返回当前 Server 绑定的凭证恢复唤醒应用服务。
|
||||
func (s *Server) credentialWakeApplication() *automationapp.CredentialWakeService {
|
||||
return s.applicationServiceSet().credentialWake
|
||||
}
|
||||
|
||||
// automationIssuesApplication 返回当前 Server 绑定的自动化异常应用服务。
|
||||
func (s *Server) automationIssuesApplication() *automationapp.IssueService {
|
||||
return s.applicationServiceSet().automationIssues
|
||||
@@ -344,16 +495,6 @@ func (s *Server) automationRulesApplication() *automationapp.RuleService {
|
||||
return s.applicationServiceSet().automationRules
|
||||
}
|
||||
|
||||
// itemBatchRunnerApplication 返回当前 Server 绑定的批量发布 worker 编排器。
|
||||
func (s *Server) itemBatchRunnerApplication() *itemapp.BatchRunner {
|
||||
return s.applicationServiceSet().itemBatchRunner
|
||||
}
|
||||
|
||||
// itemBatchRecoveryApplication 返回当前 Server 绑定的批量恢复应用服务。
|
||||
func (s *Server) itemBatchRecoveryApplication() *itemapp.BatchRecoveryService {
|
||||
return s.applicationServiceSet().itemBatchRecovery
|
||||
}
|
||||
|
||||
// itemBatchPreviewApplication 返回当前 Server 绑定的批量预检应用服务。
|
||||
func (s *Server) itemBatchPreviewApplication() *itemapp.BatchPreviewService {
|
||||
return s.applicationServiceSet().itemBatchPreview
|
||||
@@ -389,6 +530,14 @@ func (s *Server) accountSettingsApplication() *accountapp.SettingsService {
|
||||
return s.applicationServiceSet().accountSettings
|
||||
}
|
||||
|
||||
// platformCredentialApplication 返回当前 Server 绑定的平台凭证只读应用服务。
|
||||
func (s *Server) platformCredentialApplication() *accountapp.PlatformCredentialService {
|
||||
if s == nil || s.applications == nil {
|
||||
return nil
|
||||
}
|
||||
return s.applications.platformCredentials
|
||||
}
|
||||
|
||||
// authenticationApplication 返回当前 Server 绑定的用户认证应用服务。
|
||||
func (s *Server) authenticationApplication() *accountapp.AuthenticationService {
|
||||
return s.applicationServiceSet().authentication
|
||||
@@ -422,9 +571,9 @@ func (s *Server) applicationServiceSet() *applicationServices {
|
||||
if s.applications != nil {
|
||||
return s.applications
|
||||
}
|
||||
if s.dependencies == nil {
|
||||
if s.orderDependencies == nil || s.accountDependencies == nil || s.itemDependencies == nil || s.chatDependencies == nil || s.systemDependencies == nil || s.automationDependencies == nil || s.miscDependencies == nil || s.adminSettingsDependencies == nil {
|
||||
// accountLogin 仅用于零值 Server 的输入校验测试,不触发任何持久化访问。
|
||||
return &applicationServices{accountLogin: &accountLoginService{server: s}}
|
||||
return &applicationServices{accountLogin: &accountLoginService{}}
|
||||
}
|
||||
return newApplicationServices(s)
|
||||
}
|
||||
@@ -12,7 +12,7 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
|
||||
}
|
||||
// services 是统一应用服务集合。
|
||||
services := srv.applicationServiceSet()
|
||||
if services.orders == nil || services.itemSinglePublish == nil || services.itemCatalog == nil || services.itemCatalogMutation == nil || services.accountLogin == nil || services.authentication == nil || services.loginAudit == nil || services.passwordLogin == nil || services.accountDelete == nil || services.accountSettings == nil || services.analytics == nil || services.publishAutomationRules == nil || services.defaultReplies == nil || services.keywords == nil {
|
||||
if services.orders == nil || services.orderRefreshJobs == nil || services.itemBatchCoordinator == nil || services.itemSinglePublish == nil || services.itemCatalog == nil || services.itemCatalogMutation == nil || services.accountLogin == nil || services.authentication == nil || services.loginAudit == nil || services.passwordLogin == nil || services.accountDelete == nil || services.accountSettings == nil || services.uncertainNotifications == nil || services.notificationChannels == nil || services.analytics == nil || services.cards == nil || services.publishAutomationRules == nil || services.defaultReplies == nil || services.keywords == nil {
|
||||
t.Fatal("应用服务集合存在未装配的服务")
|
||||
}
|
||||
if services.orders.services == nil || services.orders.services.List == nil || services.orders.services.Detail == nil || services.orders.services.Refresh == nil || services.orders.services.RefreshJobs == nil {
|
||||
@@ -22,3 +22,35 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
|
||||
t.Fatal("应用服务访问器未返回统一装配实例")
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplicationLifecycleComponentsExposeWorkerOwnership 验证 Server 只暴露应用 worker 生命周期端口,不再提供启动入口。
|
||||
func TestApplicationLifecycleComponentsExposeWorkerOwnership(t *testing.T) {
|
||||
// srv、cleanup 保存带完整应用服务装配的测试 Server 及其资源清理函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// components 保存交给进程生命周期协调器登记的应用 worker 组件。
|
||||
components := srv.ApplicationLifecycleComponents()
|
||||
if len(components) != 3 {
|
||||
t.Fatalf("应用生命周期组件数量=%d,期望=3", len(components))
|
||||
}
|
||||
// names 保存组件稳定名称,顺序同时表达启动依赖与关闭逆序。
|
||||
names := make([]string, 0, len(components))
|
||||
// component 表示当前应用 worker 生命周期组件。
|
||||
for _, component := range components {
|
||||
names = append(names, component.Name)
|
||||
if component.Component == nil {
|
||||
t.Fatalf("组件 %q 缺少生命周期实现", component.Name)
|
||||
}
|
||||
}
|
||||
// want 是 cmd 应登记的应用 worker 稳定名称与启动顺序。
|
||||
want := []string{"order-refresh-recovery", "publish-batch-workers", "order-reconciliation-recovery"}
|
||||
if len(names) != len(want) {
|
||||
t.Fatalf("组件名称数量=%d,期望=%d", len(names), len(want))
|
||||
}
|
||||
// index 表示当前比较的生命周期组件下标。
|
||||
for index := range want {
|
||||
if names[index] != want[index] {
|
||||
t.Fatalf("组件名称[%d]=%q,期望=%q", index, names[index], want[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,8 @@ func newChatSendingApplication(server *Server) *chatapp.Service {
|
||||
if server == nil {
|
||||
return adapter.NewChatSendingApplication(nil, nil, nil, nil)
|
||||
}
|
||||
return server.dependencies.NewChatSendingApplication(server.chat, server.Manager, server.mtopClient)
|
||||
if server.chatDependencies == nil {
|
||||
return adapter.NewChatSendingApplication(server.chat, nil, server.Manager, server.mtopClient)
|
||||
}
|
||||
return server.chatDependencies.NewChatSendingApplication(server.chat, server.Manager, server.mtopClient)
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/adapter"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/auth"
|
||||
)
|
||||
@@ -57,30 +56,19 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败")
|
||||
return
|
||||
}
|
||||
if refresh && s.chat != nil && s.Manager != nil {
|
||||
if // sender、ok 保存sender、ok,供当前处理流程使用
|
||||
sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if // fetcher、ok 保存fetcher、ok,供当前处理流程使用
|
||||
fetcher, ok := sender.(interface {
|
||||
FetchChatConversations(context.Context, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
// fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
// body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用
|
||||
body, myID, fetchErr := fetcher.FetchChatConversations(fetchCtx, cursor, 100)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
// page、saveErr 保存page、saveErr,供当前处理流程使用
|
||||
page, saveErr := s.chat.RecordConversationPage(r.Context(), accountID, myID, body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存历史联系人失败")
|
||||
return
|
||||
}
|
||||
hasMore, nextCursor = page.HasMore, page.NextCursor
|
||||
} else {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, fetchErr)
|
||||
}
|
||||
}
|
||||
if refresh {
|
||||
// fetchCtx 和 cancel 限制平台联系人刷新请求的最长时间。
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
// page 和 fetchErr 保存应用层联系人分页结果及平台/持久化错误。
|
||||
page, fetchErr := s.chatApplication().RefreshConversations(fetchCtx, accountID, cursor, 100)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
hasMore, nextCursor = page.HasMore, page.NextCursor
|
||||
} else if errors.Is(fetchErr, chatapp.ErrRefreshPersist) {
|
||||
writeErr(w, http.StatusInternalServerError, "保存历史联系人失败")
|
||||
return
|
||||
} else if !errors.Is(fetchErr, chatapp.ErrRefreshUnavailable) && !errors.Is(fetchErr, chatapp.ErrOffline) {
|
||||
s.recoverExpiredSession(r.Context(), accountID, fetchErr)
|
||||
}
|
||||
}
|
||||
// rows、err 保存应用层会话摘要及查询错误。
|
||||
@@ -97,7 +85,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
resolveCancel()
|
||||
rows = refreshedRows
|
||||
if sessionErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr)
|
||||
s.recoverExpiredSession(r.Context(), accountID, sessionErr)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOsFromApplication(rows), HasMore: hasMore, NextCursor: nextCursor})
|
||||
@@ -105,7 +93,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// sendChatImage 负责send聊天图片相关处理。
|
||||
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
if !s.chatApplication().ImageUploadAvailable() {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
@@ -193,37 +181,28 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
|
||||
// limit 保存上限,供当前处理流程使用
|
||||
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
|
||||
if s.chat != nil && s.Manager != nil {
|
||||
if // sender、ok 保存sender、ok,供当前处理流程使用
|
||||
sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if // fetcher、ok 保存fetcher、ok,供当前处理流程使用
|
||||
fetcher, ok := sender.(interface {
|
||||
FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
// fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
// body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用
|
||||
body, myID, fetchErr := fetcher.FetchChatHistory(fetchCtx, chatID, cursor, limit)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
// sessions 保存sessions,供当前处理流程使用
|
||||
current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID)
|
||||
// page、saveErr 保存page、saveErr,供当前处理流程使用
|
||||
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, adapter.ChatSessionFromApplication(current), body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
|
||||
return
|
||||
}
|
||||
// current 和 identityErr 保存身份补全后的会话及平台查询错误。
|
||||
current, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), current)
|
||||
if identityErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(adapter.ChatMessagesFromDB(page.Messages)), HasMore: page.HasMore, NextCursor: page.NextCursor, Session: newChatSessionDTOFromApplication(current)})
|
||||
return
|
||||
}
|
||||
}
|
||||
// current 保存刷新前的本地会话摘要,供平台历史写入和响应展示使用。
|
||||
current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID)
|
||||
// fetchCtx 和 cancel 限制平台历史刷新请求的最长时间。
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
// refreshed 和 fetchErr 保存应用层消息分页结果及平台/持久化错误。
|
||||
refreshed, fetchErr := s.chatApplication().RefreshHistory(fetchCtx, accountID, chatID, cursor, limit, current)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
// resolved 和 identityErr 保存身份补全后的会话及平台查询错误。
|
||||
resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), refreshed.Session)
|
||||
if identityErr != nil {
|
||||
s.recoverExpiredSession(r.Context(), accountID, identityErr)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(refreshed.Messages), HasMore: refreshed.HasMore, NextCursor: refreshed.NextCursor, Session: newChatSessionDTOFromApplication(resolved)})
|
||||
return
|
||||
}
|
||||
if errors.Is(fetchErr, chatapp.ErrRefreshPersist) {
|
||||
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
|
||||
return
|
||||
}
|
||||
if !errors.Is(fetchErr, chatapp.ErrRefreshUnavailable) && !errors.Is(fetchErr, chatapp.ErrOffline) {
|
||||
s.recoverExpiredSession(r.Context(), accountID, fetchErr)
|
||||
}
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit)
|
||||
@@ -237,7 +216,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
// resolved 和 identityErr 保存身份补全后的会话及平台查询错误。
|
||||
resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), session)
|
||||
if identityErr != nil {
|
||||
s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr)
|
||||
s.recoverExpiredSession(r.Context(), accountID, identityErr)
|
||||
}
|
||||
session = resolved
|
||||
}
|
||||
@@ -257,7 +236,7 @@ type sendChatMessageRequest struct {
|
||||
|
||||
// sendChatMessage 负责send聊天消息相关处理。
|
||||
func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
if !s.chatApplication().SendingAvailable() {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
@@ -328,16 +307,16 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// chatWebSocket 负责聊天WebSocket相关处理。
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// events、unsubscribe、err 保存events、unsubscribe、err,供当前处理流程使用
|
||||
events, unsubscribe, err := s.chat.Subscribe(r.Context(), sess.UserID)
|
||||
// events、unsubscribe、err 保存应用层实时事件、清理函数和订阅错误。
|
||||
events, unsubscribe, err := s.chatApplication().Subscribe(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
|
||||
if errors.Is(err, chatapp.ErrSubscriptionUnavailable) {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
} else {
|
||||
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
// conn、err 保存conn、err,供当前处理流程使用
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
automationapp "xianyu-go/internal/application/automation"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/engine"
|
||||
)
|
||||
|
||||
// mountCookies 账号 cookie 管理端点。
|
||||
@@ -102,31 +101,14 @@ func (s *Server) writeLongLoginError(w http.ResponseWriter, err error) {
|
||||
|
||||
// updateRunningCookie 负责updateRunning登录凭证相关处理。
|
||||
func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
|
||||
s.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
// repository 提供运行时更新前的账号启用状态读取。
|
||||
repository := s.accountLoginRepositoryForServer()
|
||||
if s.Manager == nil || repository == nil || !repository.GetStatus(ctx, cookieID) {
|
||||
// runtimeService 负责唤醒凭证阻塞任务并将 Cookie 同步到账号运行实例。
|
||||
runtimeService := s.accountRuntimeApplication()
|
||||
if runtimeService == nil {
|
||||
return
|
||||
}
|
||||
if // sender、ok 保存sender、ok,供当前处理流程使用
|
||||
sender, ok := s.Manager.GetInstance(cookieID); ok {
|
||||
sender.UpdateCookie(value)
|
||||
}
|
||||
}
|
||||
|
||||
// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。
|
||||
func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
// service 提供凭证恢复后的自动化任务唤醒能力。
|
||||
service := s.credentialWakeApplication()
|
||||
if service == nil {
|
||||
return
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := service.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
// runtimeErr 保存账号运行时同步或自动化唤醒错误。
|
||||
if runtimeErr := runtimeService.UpdateCookie(ctx, cookieID, value); runtimeErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("Cookie 更新后同步账号运行时失败", "cookie_id", cookieID, "err", runtimeErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,22 +205,24 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号失败")
|
||||
return
|
||||
}
|
||||
runtime := map[string]engine.RuntimeStatus{} // runtime 保存当前账号引擎状态。
|
||||
if s.Manager != nil {
|
||||
runtime = s.Manager.RuntimeStatuses()
|
||||
// runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。
|
||||
runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context())
|
||||
if runtimeErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败")
|
||||
return
|
||||
}
|
||||
result := make(map[string]engine.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。
|
||||
for _, cid := range cookieIDs { // cid 是当前账号 ID。
|
||||
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] = engine.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
|
||||
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] = engine.RuntimeStatus{State: engine.RuntimeError, Message: "账号服务未运行", UpdatedAt: time.Now()}
|
||||
result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
@@ -1,23 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
)
|
||||
|
||||
// serverBatchManagementRuntime 将批次管理应用端口接到 Server 的 worker 生命周期边界。
|
||||
type serverBatchManagementRuntime struct {
|
||||
// server 保存批次 worker 启动与取消所需的 Server 生命周期入口。
|
||||
server *Server
|
||||
// coordinator 保存应用层批次 worker 生命周期协调器。
|
||||
coordinator *itemapp.BatchWorkerCoordinator
|
||||
}
|
||||
|
||||
// StartBatch 启动已由应用服务声明租约的批量 worker。
|
||||
func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) {
|
||||
if runtime.server == nil {
|
||||
return
|
||||
// StartBatch 启动已由应用服务声明租约的批量 worker,并返回协调器登记失败。
|
||||
func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) error {
|
||||
if runtime.server == nil || runtime.coordinator == nil {
|
||||
return errors.New("批量 worker 协调器未装配")
|
||||
}
|
||||
runtime.server.startPublishBatchWorker(runtime.server.lifecycleContext(), userID, batchID, workerToken)
|
||||
return runtime.coordinator.Start(runtime.server.lifecycleContext(), userID, batchID, workerToken)
|
||||
}
|
||||
|
||||
// CancelBatch 取消指定批次的后台 worker。
|
||||
func (runtime serverBatchManagementRuntime) CancelBatch(batchID, workerToken string) {
|
||||
if runtime.server == nil {
|
||||
if runtime.coordinator == nil {
|
||||
return
|
||||
}
|
||||
runtime.server.cancelPublishBatch(batchID, workerToken)
|
||||
_ = runtime.coordinator.Cancel(batchID, workerToken)
|
||||
}
|
||||
@@ -404,31 +404,27 @@ func (s *Server) writeItemSyncError(w http.ResponseWriter, err error) {
|
||||
func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// repository 提供平台请求所需的窄凭证视图,数据库解密和所有权读取均封装在 adapter。
|
||||
repository := s.accountLoginRepositoryForServer()
|
||||
if repository == nil {
|
||||
// service 提供消费者定义的平台凭证只读端口;本校验不会把 Cookie 明文带入 HTTP 层。
|
||||
service := s.platformCredentialApplication()
|
||||
if service == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询账号失败")
|
||||
return "", 0, false
|
||||
}
|
||||
// detail 和 err 保存账号归属及 Cookie 可用性检查结果;明文仅在当前函数返回给已授权业务适配器。
|
||||
detail, err := repository.LoadPlatformDetail(r.Context(), cookieID)
|
||||
// value、err 保存已完成归属复核的平台 Cookie 及校验错误;明文只交给当前平台调用链。
|
||||
value, err := service.LoadOwnedValue(r.Context(), sess.UserID, cookieID)
|
||||
if err != nil {
|
||||
if errors.Is(err, accountapp.ErrCredentialNotFound) {
|
||||
if errors.Is(err, accountapp.ErrCredentialNotFound) || errors.Is(err, accountapp.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return "", 0, false
|
||||
}
|
||||
if errors.Is(err, accountapp.ErrCredentialEmpty) {
|
||||
writeErr(w, http.StatusBadRequest, "账号 cookie 为空")
|
||||
return "", 0, false
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "查询账号失败")
|
||||
return "", 0, false
|
||||
}
|
||||
if detail == nil || detail.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return "", 0, false
|
||||
}
|
||||
if detail.Value == "" {
|
||||
writeErr(w, http.StatusBadRequest, "账号 cookie 为空")
|
||||
return "", 0, false
|
||||
}
|
||||
return detail.Value, sess.UserID, true
|
||||
return value, sess.UserID, true
|
||||
}
|
||||
|
||||
// listItemsByCookie 负责list商品列表By登录凭证相关处理。
|
||||
|
||||
@@ -24,9 +24,8 @@ import (
|
||||
|
||||
// maxPublishBatchRows 保存max发布批次Rows,供当前处理流程使用
|
||||
const (
|
||||
maxPublishBatchRows = 50
|
||||
publishBatchLease = 5 * time.Minute
|
||||
publishBatchJobTimeout = 2 * time.Hour
|
||||
maxPublishBatchRows = 50
|
||||
publishBatchLease = 5 * time.Minute
|
||||
)
|
||||
|
||||
// postPublishError 保存post发布错误,供当前处理流程使用
|
||||
@@ -457,58 +456,6 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
|
||||
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: startedID})
|
||||
}
|
||||
|
||||
// startPublishBatchWorker 负责开始发布批次工作器相关处理。
|
||||
func (s *Server) startPublishBatchWorker(parent context.Context, userID int64, batchID, workerToken string) {
|
||||
// workerDone 保存工作器Done,供当前处理流程使用
|
||||
workerDone := s.beginWorker()
|
||||
// #nosec G118 -- worker 由超时和 Server 根 context 共同约束。
|
||||
go func() {
|
||||
defer workerDone()
|
||||
// jobCtx、cancel 保存jobCtx、cancel,供当前处理流程使用
|
||||
jobCtx, cancel := context.WithTimeout(parent, publishBatchJobTimeout)
|
||||
s.registerPublishBatchCancel(batchID, workerToken, cancel)
|
||||
defer cancel()
|
||||
defer s.unregisterPublishBatchCancel(batchID, workerToken)
|
||||
// runner 负责批量发布的租约、逐行失败记录和最终状态收口。
|
||||
if runErr := s.itemBatchRunnerApplication().Run(jobCtx, userID, batchID, workerToken, false); runErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", runErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// RunPublishBatchRecovery 定期接管租约过期或明确因进程中断失败的批次。
|
||||
func (s *Server) RunPublishBatchRecovery(ctx context.Context) {
|
||||
s.recoverPublishBatchesOnce(ctx)
|
||||
// ticker 保存ticker,供当前处理流程使用
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.recoverPublishBatchesOnce(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartPublishBatchRecovery 先登记生命周期,再启动恢复循环,避免关闭流程在
|
||||
// goroutine 尚未调度时误判扫描器已经退出。
|
||||
// StartPublishBatchRecovery 启动发布批次Recovery。
|
||||
func (s *Server) StartPublishBatchRecovery(ctx context.Context) string {
|
||||
return s.startBackgroundTaskContext("批量发布恢复扫描器", ctx, func() {
|
||||
s.RunPublishBatchRecovery(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
// recoverPublishBatchesOnce 负责recover发布批次列表Once相关处理。
|
||||
func (s *Server) recoverPublishBatchesOnce(ctx context.Context) {
|
||||
// err 保存恢复扫描应用服务返回的全局查询错误。
|
||||
if err := s.itemBatchRecoveryApplication().Recover(ctx); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫描可恢复批量发布任务失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// downloadItemPublishBatchResult 负责download商品发布批次结果相关处理。
|
||||
func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
@@ -599,57 +546,6 @@ func publishBatchFailure(err error, batchStatus string) (string, string) {
|
||||
return message, failureKind
|
||||
}
|
||||
|
||||
// registerPublishBatchCancel 负责register发布批次取消相关处理。
|
||||
func (s *Server) registerPublishBatchCancel(batchID, workerToken string, cancel context.CancelFunc) {
|
||||
s.publishMu.Lock()
|
||||
defer s.publishMu.Unlock()
|
||||
if s.publishCancels == nil {
|
||||
s.publishCancels = make(map[string]publishBatchWorker)
|
||||
}
|
||||
if // old 保存old,供当前处理流程使用
|
||||
old := s.publishCancels[batchID]; old.cancel != nil {
|
||||
old.cancel()
|
||||
}
|
||||
s.publishCancels[batchID] = publishBatchWorker{token: workerToken, cancel: cancel}
|
||||
}
|
||||
|
||||
// unregisterPublishBatchCancel 负责unregister发布批次取消相关处理。
|
||||
func (s *Server) unregisterPublishBatchCancel(batchID, workerToken string) {
|
||||
s.publishMu.Lock()
|
||||
defer s.publishMu.Unlock()
|
||||
if // current 保存current,供当前处理流程使用
|
||||
current := s.publishCancels[batchID]; current.token == workerToken {
|
||||
delete(s.publishCancels, batchID)
|
||||
}
|
||||
}
|
||||
|
||||
// cancelPublishBatch 负责取消发布批次相关处理。
|
||||
func (s *Server) cancelPublishBatch(batchID, workerToken string) bool {
|
||||
s.publishMu.Lock()
|
||||
// worker 保存工作器,供当前处理流程使用
|
||||
worker := s.publishCancels[batchID]
|
||||
s.publishMu.Unlock()
|
||||
if worker.token != workerToken || worker.cancel == nil {
|
||||
return false
|
||||
}
|
||||
worker.cancel()
|
||||
return true
|
||||
}
|
||||
|
||||
// completeBatchPublishOutcome 将远端结果交给应用服务完成本地状态收口。
|
||||
func (s *Server) completeBatchPublishOutcome(ctx context.Context, userID int64, localService *itemapp.BatchLocalPublishService, row itemapp.BatchRow, workerToken string, outcome itemapp.BatchPublishOutcome) error {
|
||||
if localService == nil {
|
||||
return errors.New("批量发布本地收口端口未装配")
|
||||
}
|
||||
if outcome.ResponseCookieErr != nil {
|
||||
return &postPublishError{err: outcome.ResponseCookieErr}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return &postPublishError{err: ctx.Err()}
|
||||
}
|
||||
return localService.Complete(ctx, userID, row, workerToken, outcome.Result)
|
||||
}
|
||||
|
||||
// finalPublishBatchStatus 根据应用批次统计返回兼容的最终状态。
|
||||
func finalPublishBatchStatus(batch *itemapp.BatchInfo) string {
|
||||
if batch == nil {
|
||||
@@ -738,23 +634,23 @@ func (s *Server) cookieOwnedByUser(ctx context.Context, userID int64, cookieID s
|
||||
|
||||
// cookieValueForUser 读取指定用户拥有的单个账号 Cookie 明文。
|
||||
func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID string) (string, error) {
|
||||
// repository 提供按账号读取的平台窄凭证视图,解密和数据库访问均由 adapter 负责。
|
||||
repository := s.accountLoginRepositoryForServer()
|
||||
if repository == nil {
|
||||
return "", errors.New("账号凭证 repository 未初始化")
|
||||
// service 提供消费者定义的平台凭证读取端口,明文只在当前平台请求边界短暂存在。
|
||||
service := s.platformCredentialApplication()
|
||||
if service == nil {
|
||||
return "", errors.New("平台凭证读取服务未初始化")
|
||||
}
|
||||
// detail 和 err 保存账号归属与 Cookie 明文读取结果;明文只在当前发布边界短暂存在。
|
||||
detail, err := repository.LoadPlatformDetail(ctx, cookieID)
|
||||
// value 和 err 保存已通过归属复核的 Cookie 明文及读取错误;value 不进入 HTTP 响应。
|
||||
value, err := service.LoadOwnedValue(ctx, userID, cookieID)
|
||||
if err != nil {
|
||||
if errors.Is(err, accountapp.ErrCredentialNotFound) {
|
||||
if errors.Is(err, accountapp.ErrCredentialNotFound) || errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrCredentialEmpty) {
|
||||
return "", errors.New("账号不存在或 Cookie 为空")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if detail == nil || detail.UserID != userID || strings.TrimSpace(detail.Value) == "" {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return "", errors.New("账号不存在或 Cookie 为空")
|
||||
}
|
||||
return detail.Value, nil
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// cardOwnedByUser 判断指定卡券组是否属于用户。
|
||||
@@ -815,8 +711,6 @@ func firstNonEmpty(values ...string) string {
|
||||
|
||||
// serverBatchPublisher 将 Server 的商品发布细节适配为应用层批量发布端口。
|
||||
type serverBatchPublisher struct {
|
||||
// server 保存平台发布和本地商品结果适配所需的 Server 引用。
|
||||
server *Server
|
||||
// remotePort 保存已装配的平台与凭证端口,避免 worker 再进入 Server 远端逻辑。
|
||||
remotePort itemapp.BatchPublishPort
|
||||
// localService 保存已装配的本地商品、自动化规则和成功检查点收口服务。
|
||||
@@ -825,7 +719,7 @@ type serverBatchPublisher struct {
|
||||
|
||||
// PublishRow 调用批量远端端口并收口本地结果,应用层不接触数据库或 MTOP 类型。
|
||||
func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) error {
|
||||
if p.server == nil || p.remotePort == nil {
|
||||
if p.remotePort == nil {
|
||||
return errors.New("批量发布端口未装配")
|
||||
}
|
||||
if p.localService == nil {
|
||||
@@ -844,7 +738,13 @@ func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row
|
||||
if outcome.Result == nil {
|
||||
return errors.New("发布商品接口未返回结果")
|
||||
}
|
||||
return p.server.completeBatchPublishOutcome(ctx, userID, p.localService, row, workerToken, outcome)
|
||||
if outcome.ResponseCookieErr != nil {
|
||||
return &itemapp.PostPublishError{Err: outcome.ResponseCookieErr}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return &itemapp.PostPublishError{Err: ctx.Err()}
|
||||
}
|
||||
return p.localService.Complete(ctx, userID, row, workerToken, outcome.Result)
|
||||
}
|
||||
|
||||
// newItemBatchRunnerApplication 创建批量发布应用层 worker 编排器。
|
||||
@@ -858,7 +758,7 @@ func newItemBatchRunnerApplication(server *Server, remotePort itemapp.BatchPubli
|
||||
IsSessionExpired: adapter.IsSessionExpiredError,
|
||||
ClassifyFailure: publishBatchFailure,
|
||||
}
|
||||
return itemapp.NewBatchRunner(server.dependencies.NewItemBatchRepository(), serverBatchPublisher{server: server, remotePort: remotePort, localService: localService}, options)
|
||||
return itemapp.NewBatchRunner(server.itemDependencies.NewItemBatchRepository(), serverBatchPublisher{remotePort: remotePort, localService: localService}, options)
|
||||
}
|
||||
|
||||
// publishBatchLocation 保存批量发布请求中的发货地字段,不让平台 DTO 进入 HTTP 层。
|
||||
|
||||
@@ -1,36 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
import accountapp "xianyu-go/internal/application/account"
|
||||
|
||||
const (
|
||||
// loginMethodPassword 保留 Server 内部调用方使用的账号密码登录方式别名。
|
||||
loginMethodPassword = accountapp.LoginMethodPassword
|
||||
// loginMethodQRScan 保留 Server 内部调用方使用的扫码登录方式别名。
|
||||
loginMethodQRScan = accountapp.LoginMethodQRScan
|
||||
)
|
||||
|
||||
// markSuccessfulLogin 将 Server 登录成功事件交给账号应用服务审计,不在 HTTP 层组装数据库模型。
|
||||
func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
// auditService 保存应用层登录审计服务;它拥有归一化、启用和日志写入编排。
|
||||
auditService := s.loginAuditApplication()
|
||||
if auditService == nil {
|
||||
return
|
||||
}
|
||||
// auditErr 保存审计服务返回的基础设施错误;登录主流程保持旧的成功后续行为并仅记录告警。
|
||||
auditErr := auditService.RecordSuccessfulLogin(ctx, accountapp.SuccessfulLoginInput{
|
||||
AccountID: cookieID,
|
||||
UserID: userID,
|
||||
Method: method,
|
||||
Message: message,
|
||||
})
|
||||
if auditErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("记录账号登录审计失败", "cookie_id", cookieID, "method", method, "err", auditErr)
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// TestMarkSuccessfulLoginUsesApplicationAuditService 验证 Server 仅调用应用审计服务并保持登录成功持久化语义。
|
||||
func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) {
|
||||
// TestLoginAuditApplicationPersistsSuccessfulLogin 验证 Server 通过应用审计服务保持登录成功持久化语义。
|
||||
func TestLoginAuditApplicationPersistsSuccessfulLogin(t *testing.T) {
|
||||
// srv、store 和 cleanup 保存带固定管理员账号的 HTTP 测试服务及资源清理函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -15,8 +17,11 @@ func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) {
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// srv.markSuccessfulLogin 执行账号密码登录别名的成功审计。
|
||||
srv.markSuccessfulLogin(context.Background(), "acc1", admin.ID, "password_login", "账号登录成功")
|
||||
// auditErr 保存应用审计服务执行账号密码登录成功记录的结果。
|
||||
auditErr := srv.loginAuditApplication().RecordSuccessfulLogin(context.Background(), accountapp.SuccessfulLoginInput{AccountID: "acc1", UserID: admin.ID, Method: "password_login", Message: "账号登录成功"})
|
||||
if auditErr != nil {
|
||||
t.Fatalf("应用审计服务写入失败: %v", auditErr)
|
||||
}
|
||||
// summary 保存应用服务写入后的账号非敏感摘要。
|
||||
summary, summaryErr := store.Cookies.GetSummaryOwned(context.Background(), admin.ID, "acc1")
|
||||
if summaryErr != nil || summary.LoginMethod != loginMethodPassword || summary.LastLoginAt == 0 {
|
||||
@@ -29,13 +34,16 @@ func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarkSuccessfulLoginSkipsEmptyMethod 验证 Server 对缺少登录方式的兼容空操作不创建审计记录。
|
||||
func TestMarkSuccessfulLoginSkipsEmptyMethod(t *testing.T) {
|
||||
// TestLoginAuditApplicationSkipsEmptyMethod 验证应用审计服务对缺少登录方式的兼容空操作不创建审计记录。
|
||||
func TestLoginAuditApplicationSkipsEmptyMethod(t *testing.T) {
|
||||
// srv、store 和 cleanup 保存 HTTP 测试服务及资源清理函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// srv.markSuccessfulLogin 执行缺少方式的兼容调用。
|
||||
srv.markSuccessfulLogin(context.Background(), "acc1", 1, "", "不应记录")
|
||||
// auditErr 保存缺少登录方式时的兼容空操作结果。
|
||||
auditErr := srv.loginAuditApplication().RecordSuccessfulLogin(context.Background(), accountapp.SuccessfulLoginInput{AccountID: "acc1", UserID: 1, Message: "不应记录"})
|
||||
if auditErr != nil {
|
||||
t.Fatalf("缺少登录方式不应失败: %v", auditErr)
|
||||
}
|
||||
// logs 保存兼容调用后的数据库审计记录。
|
||||
logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
|
||||
if logsErr != nil {
|
||||
|
||||
@@ -22,7 +22,7 @@ func (s *Server) persistMTopCookieSessionLocked(
|
||||
if s == nil {
|
||||
return "", false, true, errors.New("cookie 会话持久化服务未初始化")
|
||||
}
|
||||
// repository 负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。
|
||||
repository := s.accountLoginRepositoryForServer()
|
||||
return adapter.PersistCookieSessionLocked(ctx, repository, detail, session)
|
||||
// sessionPort 只负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。
|
||||
sessionPort := s.platformCredentialSessionPort()
|
||||
return adapter.PersistCookieSessionLocked(ctx, sessionPort, detail, session)
|
||||
}
|
||||
@@ -170,24 +170,8 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
|
||||
// orderID 保存订单ID,供当前处理流程使用
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
OrderStatus *string `json:"order_status"`
|
||||
Status *string `json:"status"`
|
||||
ItemID *string `json:"item_id"`
|
||||
BuyerID *string `json:"buyer_id"`
|
||||
SpecName *string `json:"spec_name"`
|
||||
SpecValue *string `json:"spec_value"`
|
||||
Quantity *any `json:"quantity"`
|
||||
Amount *any `json:"amount"`
|
||||
ReceiverName *string `json:"receiver_name"`
|
||||
ReceiverPhone *string `json:"receiver_phone"`
|
||||
ReceiverAddress *string `json:"receiver_address"`
|
||||
ReceiverCity *string `json:"receiver_city"`
|
||||
ChatID *string `json:"chat_id"`
|
||||
SystemShipped *bool `json:"system_shipped"`
|
||||
ItemTitle *string `json:"item_title"`
|
||||
}
|
||||
// req 保存具名订单更新请求,兼容旧客户端的状态别名和数值字段。
|
||||
var req orderUpdateRequestDTO
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -247,11 +231,8 @@ func normalizeOrderAmount(raw string) (string, bool) {
|
||||
|
||||
// manualShipOrders 负责manualShip订单列表相关处理。
|
||||
func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
OrderIDs []string `json:"order_ids"`
|
||||
ShipMode string `json:"ship_mode"`
|
||||
}
|
||||
// req 保存具名批量发货请求。
|
||||
var req manualShipRequestDTO
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -333,11 +314,3 @@ func isStableOrderStatus(status string) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// notifyDelivery 在 Notifier 已注入时发送发货结果通知,未注入则跳过。
|
||||
func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
|
||||
if s.notifier == nil {
|
||||
return
|
||||
}
|
||||
s.notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID)
|
||||
}
|
||||
@@ -112,27 +112,6 @@ func TestCancelOrderRefreshJob(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrderRefreshWorkerCancellation 验证内存 worker 控制句柄可以被安全取消并清理。
|
||||
func TestOrderRefreshWorkerCancellation(t *testing.T) {
|
||||
// srv 保存仅用于测试 worker 控制表的 Server。
|
||||
srv := &Server{}
|
||||
// ctx、cancel 保存可观察的 worker Context 及其取消函数。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
srv.registerOrderRefreshWorker("job-1", "token-1", cancel)
|
||||
if !srv.cancelOrderRefreshWorker("job-1") {
|
||||
t.Fatal("expected active refresh worker to be cancelled")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
t.Fatal("worker context was not cancelled")
|
||||
}
|
||||
srv.unregisterOrderRefreshWorker("job-1", "token-1")
|
||||
if srv.cancelOrderRefreshWorker("job-1") {
|
||||
t.Fatal("unregistered refresh worker should not be cancellable")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
|
||||
func TestRefreshOrdersNoBrowser(t *testing.T) {
|
||||
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
|
||||
|
||||
@@ -1,25 +1,16 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
"xianyu-go/internal/auth"
|
||||
)
|
||||
|
||||
// orderRefreshJobTimeout 限制单个订单刷新后台任务的最长执行时间。
|
||||
const orderRefreshJobTimeout = 30 * time.Minute
|
||||
|
||||
// orderRefreshJobLease 为运行中的订单刷新任务提供可恢复租约。
|
||||
const orderRefreshJobLease = orderRefreshJobTimeout + time.Minute
|
||||
|
||||
// orderRefreshJobStartResponse 是创建订单刷新任务后的响应 DTO。
|
||||
type orderRefreshJobStartResponse struct {
|
||||
// Success 表示任务是否成功创建。
|
||||
@@ -34,9 +25,9 @@ type orderRefreshJobStartResponse struct {
|
||||
type orderRefreshJobStatusResponse struct {
|
||||
// Success 表示查询是否成功。
|
||||
Success bool `json:"success"`
|
||||
// JobID 是后台任务标识。
|
||||
// JobID 是任务标识。
|
||||
JobID string `json:"job_id"`
|
||||
// Status 是 queued/running/succeeded/failed 任务状态。
|
||||
// Status 是任务状态。
|
||||
Status string `json:"status"`
|
||||
// ErrorMessage 是任务失败原因。
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
@@ -54,26 +45,6 @@ type orderRefreshJobCancelResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// orderRefreshWorker 保存可被用户取消的订单刷新 worker 控制句柄。
|
||||
type orderRefreshWorker struct {
|
||||
// token 是当前 worker 的租约令牌。
|
||||
token string
|
||||
// cancel 是取消当前 worker Context 的函数。
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// orderRefreshJobRefresh 执行订单刷新业务并返回兼容 HTTP 响应模型。
|
||||
type orderRefreshJobRefresh func(context.Context, int64, string, string) (orderRefreshResponse, error)
|
||||
|
||||
// orderRefreshJobMarshal 将刷新结果序列化为可持久化的 JSON。
|
||||
type orderRefreshJobMarshal func(any) ([]byte, error)
|
||||
|
||||
// orderRefreshJobComplete 以租约令牌写入订单刷新任务终态。
|
||||
type orderRefreshJobComplete func(context.Context, string, string, string, string, string) (bool, error)
|
||||
|
||||
// errOrderRefreshJobCompletionNotApplied 表示终态写入未匹配到当前 worker 租约。
|
||||
var errOrderRefreshJobCompletionNotApplied = errors.New("订单刷新任务终态未写入")
|
||||
|
||||
// mountOrderRefreshJobRoutes 挂载订单刷新后台任务端点。
|
||||
func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) {
|
||||
r.Post(prefix+"/orders/refresh", s.startOrderRefreshJob)
|
||||
@@ -81,36 +52,26 @@ func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) {
|
||||
r.Delete(prefix+"/orders/refresh/{job_id}", s.cancelOrderRefreshJob)
|
||||
}
|
||||
|
||||
// startOrderRefreshJob 创建订单刷新任务并立即返回任务标识。
|
||||
// startOrderRefreshJob 解析筛选条件并调用应用服务创建订单刷新任务。
|
||||
func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存当前认证会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// cookieID、filterStatus 保存订单刷新筛选条件。
|
||||
cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status")
|
||||
if cookieID != "" && !s.orders().orderOwnedByUser(r.Context(), sess.UserID, cookieID) {
|
||||
// started、err 保存应用服务创建并启动任务的结果。
|
||||
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), s.lifecycleContext(), sess.UserID, cookieID, filterStatus)
|
||||
if errors.Is(err, orderapp.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
|
||||
return
|
||||
}
|
||||
// job 保存待持久化的订单刷新任务。
|
||||
job := &orderapp.RefreshJob{
|
||||
ID: "order-refresh-" + randomHex(16), UserID: sess.UserID,
|
||||
CookieID: cookieID, FilterStatus: filterStatus,
|
||||
}
|
||||
// err 表示创建任务的数据库错误。
|
||||
if err := s.orders().services.RefreshJobs.Create(r.Context(), job); err != nil {
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("创建订单刷新任务失败", "err", err)
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "创建订单刷新任务失败")
|
||||
return
|
||||
}
|
||||
// token 保存本次执行者的租约令牌。
|
||||
token := randomHex(16)
|
||||
// claimed、claimErr 保存任务抢占结果及错误。
|
||||
claimed, claimErr := s.orders().services.RefreshJobs.Claim(r.Context(), job.ID, token, time.Now().Add(orderRefreshJobLease).Unix())
|
||||
if claimErr != nil || !claimed {
|
||||
writeErr(w, http.StatusInternalServerError, "启动订单刷新任务失败")
|
||||
return
|
||||
}
|
||||
s.startOrderRefreshWorker(job, token)
|
||||
writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: job.ID, Status: "running"})
|
||||
writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: started.Job.ID, Status: "running"})
|
||||
}
|
||||
|
||||
// getOrderRefreshJob 返回当前用户拥有的订单刷新任务状态和结果。
|
||||
@@ -119,8 +80,8 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// jobID 保存路径中的订单刷新任务标识。
|
||||
jobID := chi.URLParam(r, "job_id")
|
||||
// job、err 保存任务读取结果及错误。
|
||||
job, err := s.orders().services.RefreshJobs.Get(r.Context(), sess.UserID, jobID)
|
||||
// job、err 保存应用服务读取结果及错误。
|
||||
job, err := s.orderRefreshJobsApplication().GetJob(r.Context(), sess.UserID, jobID)
|
||||
if errors.Is(err, orderapp.ErrRefreshJobNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "订单刷新任务不存在")
|
||||
return
|
||||
@@ -132,8 +93,8 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
// response 保存任务状态响应 DTO。
|
||||
response := orderRefreshJobStatusResponse{Success: true, JobID: job.ID, Status: job.Status, ErrorMessage: job.ErrorMessage}
|
||||
if job.ResultJSON != "" && job.ResultJSON != "{}" {
|
||||
// result 保存成功任务的具名刷新结果。
|
||||
var result orderRefreshResponse
|
||||
// result 保存应用层稳定结果模型,避免 HTTP 层承担持久化结果形状。
|
||||
var result orderapp.RefreshJobResult
|
||||
// err 表示任务结果 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(job.ResultJSON), &result); err != nil {
|
||||
if s.Logger != nil {
|
||||
@@ -142,244 +103,58 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "读取订单刷新结果失败")
|
||||
return
|
||||
}
|
||||
response.Result = &result
|
||||
// mapped 保存转换后的 HTTP 兼容结果 DTO。
|
||||
mapped := orderRefreshResponseFromJobResult(result)
|
||||
response.Result = &mapped
|
||||
}
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
// cancelOrderRefreshJob 按当前用户归属取消订单刷新任务并通知运行中的 worker。
|
||||
// cancelOrderRefreshJob 按当前用户归属取消任务,并由应用服务通知运行中的 worker。
|
||||
func (s *Server) cancelOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存当前认证会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// jobID 保存路径中的订单刷新任务标识。
|
||||
jobID := chi.URLParam(r, "job_id")
|
||||
// cancelled、err 保存数据库取消结果及错误。
|
||||
cancelled, err := s.orders().services.RefreshJobs.Cancel(r.Context(), sess.UserID, jobID)
|
||||
// result、err 保存应用服务取消结果及错误。
|
||||
result, err := s.orderRefreshJobsApplication().CancelForUser(r.Context(), sess.UserID, jobID)
|
||||
if errors.Is(err, orderapp.ErrRefreshJobNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "订单刷新任务不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "取消订单刷新任务失败")
|
||||
return
|
||||
}
|
||||
if cancelled {
|
||||
s.cancelOrderRefreshWorker(jobID)
|
||||
writeJSON(w, http.StatusOK, orderRefreshJobCancelResponse{Success: true, JobID: jobID, Status: "cancelled"})
|
||||
return
|
||||
}
|
||||
// job、getErr 保存取消未生效时的当前任务状态及查询错误。
|
||||
job, getErr := s.orders().services.RefreshJobs.Get(r.Context(), sess.UserID, jobID)
|
||||
if errors.Is(getErr, orderapp.ErrRefreshJobNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "订单刷新任务不存在")
|
||||
return
|
||||
}
|
||||
if getErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取订单刷新任务失败")
|
||||
return
|
||||
}
|
||||
if job.Status == "cancelled" {
|
||||
if result.Cancelled || (result.Job != nil && result.Job.Status == "cancelled") {
|
||||
writeJSON(w, http.StatusOK, orderRefreshJobCancelResponse{Success: true, JobID: jobID, Status: "cancelled"})
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusConflict, "订单刷新任务已结束,无法取消")
|
||||
}
|
||||
|
||||
// startOrderRefreshWorker 启动受 Server 生命周期管理的订单刷新 worker。
|
||||
func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string) {
|
||||
if job == nil {
|
||||
return
|
||||
// orderRefreshResponseFromJobResult 将应用层任务结果映射为历史 HTTP 响应 DTO。
|
||||
func orderRefreshResponseFromJobResult(result orderapp.RefreshJobResult) orderRefreshResponse {
|
||||
// results 保存转换后的 HTTP 结果行。
|
||||
results := make([]orderRefreshResultDTO, 0, len(result.Results))
|
||||
// item 表示当前应用层任务结果行。
|
||||
for _, item := range result.Results {
|
||||
results = append(results, orderRefreshResultDTO{
|
||||
Success: item.Success, CookieID: item.CookieID, Discovered: item.Discovered,
|
||||
Updated: item.Updated, SoftDeleted: item.SoftDeleted, OrderID: item.OrderID,
|
||||
Stage: item.Stage, Message: item.Message, Error: item.Error,
|
||||
OldStatus: item.OldStatus, NewStatus: item.NewStatus,
|
||||
})
|
||||
}
|
||||
// parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。
|
||||
parent := s.lifecycleContext()
|
||||
if parent == nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("订单刷新任务缺少 Server 生命周期上下文", "job_id", job.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
// jobCtx、cancel 限制后台任务执行时间并支持用户取消。
|
||||
jobCtx, cancel := context.WithTimeout(parent, orderRefreshJobTimeout)
|
||||
s.registerOrderRefreshWorker(job.ID, token, cancel)
|
||||
s.startBackgroundTaskResult("订单刷新任务", jobCtx, func() error {
|
||||
defer cancel()
|
||||
defer s.unregisterOrderRefreshWorker(job.ID, token)
|
||||
// runErr 保存订单刷新业务或终态写入错误,供后台任务日志观测。
|
||||
runErr := s.runOrderRefreshJob(jobCtx, job, token)
|
||||
if runErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("订单刷新后台任务结束", "job_id", job.ID, "err", runErr)
|
||||
}
|
||||
if jobCtx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return runErr
|
||||
})
|
||||
}
|
||||
|
||||
// registerOrderRefreshWorker 登记可取消的订单刷新 worker。
|
||||
func (s *Server) registerOrderRefreshWorker(jobID, token string, cancel context.CancelFunc) {
|
||||
s.orderRefreshMu.Lock()
|
||||
defer s.orderRefreshMu.Unlock()
|
||||
if s.orderRefreshCancels == nil {
|
||||
s.orderRefreshCancels = make(map[string]orderRefreshWorker)
|
||||
}
|
||||
// previous 保存同一任务的旧 worker 控制句柄。
|
||||
previous := s.orderRefreshCancels[jobID]
|
||||
if previous.cancel != nil && previous.token != token {
|
||||
previous.cancel()
|
||||
}
|
||||
s.orderRefreshCancels[jobID] = orderRefreshWorker{token: token, cancel: cancel}
|
||||
}
|
||||
|
||||
// unregisterOrderRefreshWorker 在 worker 退出时清理控制句柄。
|
||||
func (s *Server) unregisterOrderRefreshWorker(jobID, token string) {
|
||||
s.orderRefreshMu.Lock()
|
||||
defer s.orderRefreshMu.Unlock()
|
||||
// current 保存当前任务登记的 worker 控制句柄。
|
||||
current := s.orderRefreshCancels[jobID]
|
||||
if current.token == token {
|
||||
delete(s.orderRefreshCancels, jobID)
|
||||
}
|
||||
}
|
||||
|
||||
// cancelOrderRefreshWorker 取消内存中的订单刷新 worker,不改变数据库终态。
|
||||
func (s *Server) cancelOrderRefreshWorker(jobID string) bool {
|
||||
s.orderRefreshMu.Lock()
|
||||
// worker 保存当前任务的取消控制句柄。
|
||||
worker := s.orderRefreshCancels[jobID]
|
||||
s.orderRefreshMu.Unlock()
|
||||
if worker.cancel == nil {
|
||||
return false
|
||||
}
|
||||
worker.cancel()
|
||||
return true
|
||||
}
|
||||
|
||||
// runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。
|
||||
func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) error {
|
||||
// orders 保存当前 Server 绑定的订单应用适配器。
|
||||
orders := s.orders()
|
||||
if orders == nil || orders.services == nil || orders.services.Refresh == nil || orders.services.RefreshJobs == nil {
|
||||
return errors.New("订单刷新任务依赖未初始化")
|
||||
}
|
||||
return runOrderRefreshJobWith(ctx, job, token, orders.Refresh, json.Marshal, orders.services.RefreshJobs.Complete)
|
||||
}
|
||||
|
||||
// runOrderRefreshJobWith 执行可注入依赖的订单刷新 worker,便于确定性验证终态边界。
|
||||
func runOrderRefreshJobWith(ctx context.Context, job *orderapp.RefreshJob, token string, refresh orderRefreshJobRefresh, marshal orderRefreshJobMarshal, complete orderRefreshJobComplete) error {
|
||||
if ctx == nil {
|
||||
return errors.New("订单刷新任务 Context 不能为空")
|
||||
}
|
||||
if job == nil {
|
||||
return errors.New("订单刷新任务不能为空")
|
||||
}
|
||||
if refresh == nil || marshal == nil || complete == nil {
|
||||
return errors.New("订单刷新任务依赖未初始化")
|
||||
}
|
||||
// result、err 保存订单刷新业务结果及错误。
|
||||
result, err := refresh(ctx, job.UserID, job.CookieID, job.FilterStatus)
|
||||
if err != nil {
|
||||
// completeErr 保存失败终态写入错误。
|
||||
completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", err.Error())
|
||||
if completeErr != nil {
|
||||
return errors.Join(err, completeErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
// resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。
|
||||
resultJSON, marshalErr := marshal(result)
|
||||
if marshalErr != nil {
|
||||
// completeErr 保存序列化失败终态写入错误。
|
||||
completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", marshalErr.Error())
|
||||
if completeErr != nil {
|
||||
return errors.Join(marshalErr, completeErr)
|
||||
}
|
||||
return marshalErr
|
||||
}
|
||||
// completeErr 保存成功终态写入错误。
|
||||
return completeOrderRefreshJob(ctx, complete, job.ID, token, "succeeded", string(resultJSON), "")
|
||||
}
|
||||
|
||||
// completeOrderRefreshJob 写入终态并把数据库错误或租约失配转换为可观测错误。
|
||||
func completeOrderRefreshJob(ctx context.Context, complete orderRefreshJobComplete, jobID, token, status, resultJSON, errorMessage string) error {
|
||||
if ctx == nil {
|
||||
return errors.New("订单刷新任务终态写入 Context 不能为空")
|
||||
}
|
||||
if complete == nil {
|
||||
return errors.New("订单刷新任务终态写入依赖未初始化")
|
||||
}
|
||||
// applied、err 保存终态写入是否命中当前租约及数据库错误。
|
||||
applied, err := complete(ctx, jobID, token, status, resultJSON, errorMessage)
|
||||
if err != nil {
|
||||
return fmt.Errorf("订单刷新任务终态写入失败: %w", err)
|
||||
}
|
||||
if !applied {
|
||||
return fmt.Errorf("%w: job_id=%s", errOrderRefreshJobCompletionNotApplied, jobID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunOrderRefreshRecovery 扫描并重新执行租约过期的订单刷新任务。
|
||||
func (s *Server) RunOrderRefreshRecovery(ctx context.Context) {
|
||||
s.recoverOrderRefreshJobsOnce(ctx)
|
||||
// ticker 保存恢复扫描间隔计时器。
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.recoverOrderRefreshJobsOnce(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartOrderRefreshRecovery 启动受 Server 生命周期管理的订单刷新恢复扫描器。
|
||||
func (s *Server) StartOrderRefreshRecovery(ctx context.Context) string {
|
||||
return s.startBackgroundTaskContext("订单刷新恢复扫描器", ctx, func() {
|
||||
s.RunOrderRefreshRecovery(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
// recoverOrderRefreshJobsOnce 将过期任务重新入队并启动新的 worker。
|
||||
func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) {
|
||||
// jobs、err 保存可恢复任务及扫描错误。
|
||||
jobs, err := s.orders().services.RefreshJobs.Recoverable(ctx, time.Now().Unix(), 20)
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("扫描订单刷新恢复任务失败", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
// job 表示当前待恢复的订单刷新任务。
|
||||
for _, job := range jobs {
|
||||
// requeued、requeueErr 保存重新入队结果及错误。
|
||||
requeued, requeueErr := s.orders().services.RefreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix())
|
||||
if requeueErr != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("重新入队订单刷新任务失败", "job_id", job.ID, "err", requeueErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !requeued {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("重新入队订单刷新任务未生效", "job_id", job.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// token 保存恢复 worker 的新租约令牌。
|
||||
token := randomHex(16)
|
||||
// claimed、claimErr 保存恢复任务抢占结果及错误。
|
||||
claimed, claimErr := s.orders().services.RefreshJobs.Claim(ctx, job.ID, token, time.Now().Add(orderRefreshJobLease).Unix())
|
||||
if claimErr != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("抢占恢复订单刷新任务失败", "job_id", job.ID, "err", claimErr)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !claimed {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("抢占恢复订单刷新任务未生效", "job_id", job.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
s.startOrderRefreshWorker(&job, token)
|
||||
return orderRefreshResponse{
|
||||
PartialFailure: result.PartialFailure,
|
||||
Message: result.Message,
|
||||
Summary: orderRefreshSummary{
|
||||
Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated,
|
||||
SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal,
|
||||
Total: result.Summary.Total, Updated: result.Summary.Updated,
|
||||
NoChange: result.Summary.NoChange, Failed: result.Summary.Failed,
|
||||
},
|
||||
Results: results,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
)
|
||||
|
||||
// orderRefreshJobRefresh 是历史生命周期测试使用的 HTTP 结果回调类型。
|
||||
type orderRefreshJobRefresh func(context.Context, int64, string, string) (orderRefreshResponse, error)
|
||||
|
||||
// orderRefreshJobMarshal 是历史生命周期测试使用的结果序列化回调类型。
|
||||
type orderRefreshJobMarshal func(any) ([]byte, error)
|
||||
|
||||
// orderRefreshJobComplete 是历史生命周期测试使用的任务终态写入回调类型。
|
||||
type orderRefreshJobComplete func(context.Context, string, string, string, string, string) (bool, error)
|
||||
|
||||
// errOrderRefreshJobCompletionNotApplied 保留旧测试对应用层租约失配错误的引用。
|
||||
var errOrderRefreshJobCompletionNotApplied = orderapp.ErrRefreshJobCompletionNotApplied
|
||||
|
||||
// orderRefreshLifecycleRefresher 将历史 HTTP 结果回调适配到订单应用刷新结果。
|
||||
type orderRefreshLifecycleRefresher struct {
|
||||
// refresh 保存测试注入的刷新业务回调。
|
||||
refresh orderRefreshJobRefresh
|
||||
}
|
||||
|
||||
// Refresh 执行测试回调并把 HTTP 结果转换为应用层刷新结果。
|
||||
func (refresher orderRefreshLifecycleRefresher) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderapp.RefreshResult, error) {
|
||||
// result、err 保存历史刷新回调的结果及错误。
|
||||
result, err := refresher.refresh(ctx, userID, cookieID, status)
|
||||
if err != nil {
|
||||
return orderapp.RefreshResult{}, err
|
||||
}
|
||||
return orderapp.RefreshResult{PartialFailure: result.PartialFailure, Message: result.Message, Summary: orderapp.RefreshSummary{
|
||||
Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated,
|
||||
SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal,
|
||||
Total: result.Summary.Total, Updated: result.Summary.Updated,
|
||||
NoChange: result.Summary.NoChange, Failed: result.Summary.Failed,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// orderRefreshLifecycleRepository 将测试终态回调适配到应用层任务仓储。
|
||||
type orderRefreshLifecycleRepository struct {
|
||||
// complete 保存测试注入的终态写入回调。
|
||||
complete orderRefreshJobComplete
|
||||
}
|
||||
|
||||
// Create 满足订单刷新任务仓储接口;生命周期测试不验证创建流程。
|
||||
func (repository orderRefreshLifecycleRepository) Create(context.Context, *orderapp.RefreshJob) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 满足订单刷新任务仓储接口;生命周期测试不读取任务。
|
||||
func (repository orderRefreshLifecycleRepository) Get(context.Context, int64, string) (*orderapp.RefreshJob, error) {
|
||||
return nil, orderapp.ErrRefreshJobNotFound
|
||||
}
|
||||
|
||||
// Claim 满足订单刷新任务仓储接口;生命周期测试直接执行已声明租约的任务。
|
||||
func (repository orderRefreshLifecycleRepository) Claim(context.Context, string, string, int64) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Cancel 满足订单刷新任务仓储接口;生命周期测试不验证取消持久化。
|
||||
func (repository orderRefreshLifecycleRepository) Cancel(context.Context, int64, string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Complete 调用测试注入的终态写入回调。
|
||||
func (repository orderRefreshLifecycleRepository) Complete(ctx context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) {
|
||||
return repository.complete(ctx, jobID, token, status, resultJSON, errorMessage)
|
||||
}
|
||||
|
||||
// Recoverable 满足订单刷新任务仓储接口;生命周期测试不验证恢复扫描。
|
||||
func (repository orderRefreshLifecycleRepository) Recoverable(context.Context, int64, int) ([]orderapp.RefreshJob, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// RequeueExpired 满足订单刷新任务仓储接口;生命周期测试不验证恢复扫描。
|
||||
func (repository orderRefreshLifecycleRepository) RequeueExpired(context.Context, string, int64) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// runOrderRefreshJobWith 通过应用层 runner 执行历史生命周期测试的可注入任务。
|
||||
func runOrderRefreshJobWith(ctx context.Context, job *orderapp.RefreshJob, token string, refresh orderRefreshJobRefresh, marshal orderRefreshJobMarshal, complete orderRefreshJobComplete) error {
|
||||
if refresh == nil || marshal == nil || complete == nil {
|
||||
return errors.New("订单刷新测试依赖未初始化")
|
||||
}
|
||||
// repository 保存测试终态回调的应用仓储适配器。
|
||||
repository := orderRefreshLifecycleRepository{complete: complete}
|
||||
// runner、err 保存应用层订单刷新运行器及构造错误。
|
||||
runner, err := orderapp.NewRefreshJobRunner(repository, orderRefreshLifecycleRefresher{refresh: refresh}, orderapp.RefreshJobRunnerOptions{
|
||||
MarshalResult: func(result orderapp.RefreshJobResult) ([]byte, error) { return marshal(result) },
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runner.RunJob(ctx, job, token)
|
||||
}
|
||||
@@ -203,12 +203,9 @@ func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) {
|
||||
// srv、store、cleanup 保存测试服务、数据库和清理函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// lifecycleCtx、cancel 是已取消的 Server 生命周期上下文。
|
||||
// lifecycleCtx、cancel 是已取消的应用生命周期上下文。
|
||||
lifecycleCtx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
srv.lifecycleMu.Lock()
|
||||
srv.lifecycleCtx = lifecycleCtx
|
||||
srv.lifecycleMu.Unlock()
|
||||
// admin、err 保存任务所属用户及查询错误。
|
||||
admin, err := store.Users.GetByUsername(context.Background(), "admin")
|
||||
if err != nil {
|
||||
@@ -229,8 +226,19 @@ func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) {
|
||||
}
|
||||
// job 是传给后台 worker 的应用层任务模型。
|
||||
job := &orderapp.RefreshJob{ID: dbJob.ID, UserID: dbJob.UserID}
|
||||
srv.startOrderRefreshWorker(job, token)
|
||||
srv.WaitForBackground()
|
||||
// runner、runnerErr 保存直接由应用层拥有的订单刷新 worker。
|
||||
runner, runnerErr := orderapp.NewRefreshJobRunner(srv.orders().services.RefreshJobs, srv.orders().services.Refresh, orderapp.RefreshJobRunnerOptions{})
|
||||
if runnerErr != nil {
|
||||
t.Fatalf("构造订单刷新运行器: %v", runnerErr)
|
||||
}
|
||||
// startErr 保存应用层 worker 启动错误。
|
||||
if startErr := runner.StartJob(lifecycleCtx, job, token); startErr != nil {
|
||||
t.Fatalf("启动订单刷新 worker: %v", startErr)
|
||||
}
|
||||
// closeErr 保存应用层 worker 关闭错误。
|
||||
if closeErr := runner.Close(context.Background()); closeErr != nil {
|
||||
t.Fatalf("关闭订单刷新 worker: %v", closeErr)
|
||||
}
|
||||
// persisted、err 保存 worker 结束后的任务状态及查询错误。
|
||||
persisted, err := store.OrderRefreshJobs.Get(context.Background(), admin.ID, dbJob.ID)
|
||||
if err != nil {
|
||||
|
||||
@@ -18,31 +18,20 @@ type serverOrderRuntimeAdapter struct {
|
||||
|
||||
// newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。
|
||||
func newServerOrderRuntime(server *Server, reconciliation orderapp.ReconciliationRecorder) serverOrderRuntimeAdapter {
|
||||
// hooks 保存 Server 运行时回调,避免适配器反向依赖 Server 包。
|
||||
// hooks 保存 adapter 内部构造的账号、自动化、通知和平台回调,Server 不再编排业务闭包。
|
||||
hooks := adapter.OrderRuntimeHooks{}
|
||||
if server != nil {
|
||||
hooks = adapter.OrderRuntimeHooks{
|
||||
Client: server.mtopClient,
|
||||
ClientAvailable: func() bool { return server.MTop != nil },
|
||||
AccountRunning: func(cookieID string) bool {
|
||||
if server.Manager == nil {
|
||||
return false
|
||||
}
|
||||
// _, running 保存账号运行实例是否存在。
|
||||
_, running := server.Manager.GetInstance(cookieID)
|
||||
return running
|
||||
},
|
||||
AutomationReady: func() bool { return server.Manager != nil && server.automation != nil },
|
||||
ManualFullDelivery: func(ctx context.Context, order *orderapp.Order) (int, error) {
|
||||
if server.automation == nil {
|
||||
return 0, errors.New("自动化中心未初始化")
|
||||
}
|
||||
return server.automation.ManualFullDelivery(ctx, adapter.OrderForAutomation(order))
|
||||
},
|
||||
UpdateRunningCookie: server.updateRunningCookie,
|
||||
NotifyDelivery: server.notifyDelivery,
|
||||
RecoverExpiredSession: server.recoverExpiredMTOPSession,
|
||||
// automation、notifier 显式保持 nil 接口语义,避免把 nil 指针转换为非空接口后误报能力已装配。
|
||||
var automation adapter.OrderAutomation
|
||||
if server.automation != nil {
|
||||
automation = server.automation
|
||||
}
|
||||
// notifier 只在真实通知器存在时转换为接口,避免 nil 指针伪装成已装配能力。
|
||||
var notifier adapter.OrderNotifier
|
||||
if server.notifier != nil {
|
||||
notifier = server.notifier
|
||||
}
|
||||
hooks = adapter.NewOrderRuntimeHooks(server.mtopClient, server.Manager, automation, notifier, server.updateRunningCookie, server.sessionRecoveryCallback())
|
||||
}
|
||||
// logger 保存 Server 使用的日志器;适配器会在缺失时使用默认日志器。
|
||||
var logger = (*slog.Logger)(nil)
|
||||
@@ -54,7 +43,7 @@ func newServerOrderRuntime(server *Server, reconciliation orderapp.Reconciliatio
|
||||
if server == nil {
|
||||
runtime = adapter.NewOrderRuntime(nil, hooks, reconciliation, logger)
|
||||
} else {
|
||||
runtime = server.dependencies.NewOrderRuntime(hooks, reconciliation, logger)
|
||||
runtime = server.orderDependencies.NewOrderRuntime(hooks, reconciliation, logger)
|
||||
}
|
||||
return serverOrderRuntimeAdapter{runtime: runtime}
|
||||
}
|
||||
@@ -191,8 +180,6 @@ func (a serverOrderRuntimeAdapter) IsSessionExpired(err error) bool {
|
||||
type orderHTTPAdapter struct {
|
||||
// services 保存应用层统一构造的订单业务服务集合。
|
||||
services *orderapp.ServiceSet
|
||||
// repository 保存 HTTP 适配器需要的账号归属查询 Port。
|
||||
repository orderapp.Repository
|
||||
}
|
||||
|
||||
// RefreshSingle 刷新单个订单详情并转换为兼容 HTTP 响应模型。
|
||||
@@ -232,34 +219,48 @@ func (a *orderHTTPAdapter) Refresh(ctx context.Context, userID int64, cookieID,
|
||||
return orderRefreshResponse{PartialFailure: result.PartialFailure, Message: result.Message, Summary: orderRefreshSummary{Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated, SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal, Total: result.Summary.Total, Updated: result.Summary.Updated, NoChange: result.Summary.NoChange, Failed: result.Summary.Failed}, Results: refreshResultsFromApplication(result.Results)}, nil
|
||||
}
|
||||
|
||||
// refreshResultsFromApplication 将应用层刷新结果转换为兼容动态结果行。
|
||||
func refreshResultsFromApplication(items []orderapp.RefreshOrderResult) []map[string]any {
|
||||
// results 保存兼容客户端使用的结果行。
|
||||
results := make([]map[string]any, 0, len(items))
|
||||
// intPointer 为结果 DTO 创建整数指针,使零值也能按兼容契约显式返回。
|
||||
func intPointer(value int) *int {
|
||||
return &value
|
||||
}
|
||||
|
||||
// boolPointer 为结果 DTO 创建布尔指针,使 false 也能按兼容契约显式返回。
|
||||
func boolPointer(value bool) *bool {
|
||||
return &value
|
||||
}
|
||||
|
||||
// refreshResultsFromApplication 将应用层刷新结果转换为具名结果行。
|
||||
func refreshResultsFromApplication(items []orderapp.RefreshOrderResult) []orderRefreshResultDTO {
|
||||
// results 保存兼容客户端使用的具名结果行,避免响应契约依赖动态 map。
|
||||
results := make([]orderRefreshResultDTO, 0, len(items))
|
||||
// item 是当前应用层刷新结果。
|
||||
for _, item := range items {
|
||||
// row 保存当前兼容响应行。
|
||||
row := map[string]any{"success": item.Success}
|
||||
row := orderRefreshResultDTO{Success: item.Success}
|
||||
if item.CookieID != "" {
|
||||
row["cookie_id"], row["discovered"], row["updated"] = item.CookieID, item.Discovered, item.Updated
|
||||
row.CookieID = item.CookieID
|
||||
row.Discovered = intPointer(item.Discovered)
|
||||
row.Updated = intPointer(item.Updated)
|
||||
if item.Success {
|
||||
row["soft_deleted"] = item.SoftDeleted
|
||||
// softDeleted 表示本次账号刷新是否标记了失效订单。
|
||||
softDeleted := item.SoftDeleted != 0
|
||||
row.SoftDeleted = boolPointer(softDeleted)
|
||||
}
|
||||
}
|
||||
if item.OrderID != "" {
|
||||
row["order_id"] = item.OrderID
|
||||
row.OrderID = item.OrderID
|
||||
}
|
||||
if item.Stage != "" {
|
||||
row["stage"] = item.Stage
|
||||
row.Stage = item.Stage
|
||||
}
|
||||
if item.Message != "" {
|
||||
row["message"] = item.Message
|
||||
row.Message = item.Message
|
||||
}
|
||||
if item.Error != "" {
|
||||
row["error"] = item.Error
|
||||
row.Error = item.Error
|
||||
}
|
||||
if item.OldStatus != "" || item.NewStatus != "" {
|
||||
row["old_status"], row["new_status"] = item.OldStatus, item.NewStatus
|
||||
row.OldStatus, row.NewStatus = item.OldStatus, item.NewStatus
|
||||
}
|
||||
results = append(results, row)
|
||||
}
|
||||
@@ -314,13 +315,6 @@ func (s *Server) orders() *orderHTTPAdapter {
|
||||
return s.applicationServiceSet().orders
|
||||
}
|
||||
|
||||
// orderOwnedByUser 判断订单服务使用的账号是否归属于当前用户。
|
||||
func (a *orderHTTPAdapter) orderOwnedByUser(ctx context.Context, userID int64, cookieID string) bool {
|
||||
// owned 和 err 保存账号归属检查结果。
|
||||
owned, err := a.repository.ExistsOwned(ctx, userID, cookieID)
|
||||
return err == nil && owned
|
||||
}
|
||||
|
||||
// orderListQuery 描述订单列表的业务查询条件。
|
||||
type orderListQuery struct {
|
||||
// UserID 是当前登录用户标识。
|
||||
@@ -533,8 +527,8 @@ type orderImportResult struct {
|
||||
SuccessCount int
|
||||
// FailedCount 是失败导入数。
|
||||
FailedCount int
|
||||
// Results 是逐单结果。
|
||||
Results []map[string]any
|
||||
// Results 是逐单具名结果。
|
||||
Results []orderImportResultDTO
|
||||
}
|
||||
|
||||
// Import 按当前用户账号所有权逐单导入订单,并为订单关联商品补全基础信息。
|
||||
@@ -570,11 +564,11 @@ func importOrderFromRaw(raw map[string]any) orderapp.ImportOrder {
|
||||
|
||||
// orderImportResultFromApplication 将应用层导入结果转换为旧 HTTP 响应兼容模型。
|
||||
func orderImportResultFromApplication(result orderapp.ImportResult) orderImportResult {
|
||||
// results 保存兼容客户端使用的逐条动态结果。
|
||||
results := make([]map[string]any, 0, len(result.Results))
|
||||
// results 保存兼容客户端使用的逐条具名结果。
|
||||
results := make([]orderImportResultDTO, 0, len(result.Results))
|
||||
// item 保存当前应用层导入结果行。
|
||||
for _, item := range result.Results {
|
||||
results = append(results, map[string]any{"order_id": item.OrderID, "success": item.Success, "message": item.Message})
|
||||
results = append(results, orderImportResultDTO{OrderID: item.OrderID, Success: item.Success, Message: item.Message})
|
||||
}
|
||||
return orderImportResult{Total: result.Total, SuccessCount: result.SuccessCount, FailedCount: result.FailedCount, Results: results}
|
||||
}
|
||||
@@ -595,8 +589,8 @@ type manualShipResult struct {
|
||||
SuccessCount int
|
||||
// FailedCount 是失败发货数。
|
||||
FailedCount int
|
||||
// Results 是逐单结果。
|
||||
Results []map[string]any
|
||||
// Results 是逐单具名结果。
|
||||
Results []orderMutationResultDTO
|
||||
}
|
||||
|
||||
// ManualShip 执行状态确认或完整自动化发货,并集中处理逐单失败而不中断批次的规则。
|
||||
@@ -611,15 +605,15 @@ func (a *orderHTTPAdapter) ManualShip(ctx context.Context, request manualShipReq
|
||||
|
||||
// manualShipResultFromApplication 将应用层手动发货结果转换为旧 HTTP 响应兼容模型。
|
||||
func manualShipResultFromApplication(result orderapp.ManualShipResult) manualShipResult {
|
||||
// results 保存兼容客户端使用的逐条动态结果。
|
||||
results := make([]map[string]any, 0, len(result.Results))
|
||||
// results 保存兼容客户端使用的逐条具名结果。
|
||||
results := make([]orderMutationResultDTO, 0, len(result.Results))
|
||||
// item 保存当前应用层手动发货结果行。
|
||||
for _, item := range result.Results {
|
||||
// row 保存兼容客户端使用的单条结果。
|
||||
row := map[string]any{"order_id": item.OrderID, "status": item.Status, "success": item.Success, "message": item.Message}
|
||||
row := orderMutationResultDTO{OrderID: item.OrderID, Status: item.Status, Success: item.Success, Message: item.Message}
|
||||
if item.ReconciliationFieldsPresent {
|
||||
row["reconciliation_id"] = item.ReconciliationID
|
||||
row["reconciliation_warning"] = item.ReconciliationWarning
|
||||
row.ReconciliationID = item.ReconciliationID
|
||||
row.ReconciliationWarning = item.ReconciliationWarning
|
||||
}
|
||||
results = append(results, row)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/adapter"
|
||||
"xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// serverPlatformQRFake 是 Server 平台访问器测试使用的二维码服务替身。
|
||||
type serverPlatformQRFake struct{}
|
||||
|
||||
// GenerateQRCode 返回固定二维码数据,验证 Server 不参与平台协议编排。
|
||||
func (serverPlatformQRFake) GenerateQRCode(context.Context) (string, string, error) {
|
||||
return "session", "https://example.test/qr", nil
|
||||
}
|
||||
|
||||
// GetSessionStatus 返回固定轮询状态,验证二维码能力可由显式依赖提供。
|
||||
func (serverPlatformQRFake) GetSessionStatus(string) map[string]any {
|
||||
return map[string]any{"status": "waiting"}
|
||||
}
|
||||
|
||||
// CompleteVerification 返回脱敏验证结果,测试不输出真实凭证。
|
||||
func (serverPlatformQRFake) CompleteVerification(context.Context, string) (string, string, error) {
|
||||
return "masked-cookie", "account", nil
|
||||
}
|
||||
|
||||
// TestServerPlatformAccessorsUseInjectedDependencies 验证生产访问器读取构造阶段的平台依赖。
|
||||
func TestServerPlatformAccessorsUseInjectedDependencies(t *testing.T) {
|
||||
// mtopClient、longLoginClient 和 qrService 保存本测试注入的客户端能力。
|
||||
mtopClient := adapter.NewMTOPClient()
|
||||
// longLoginClient 保存注入的长登录协议实现。
|
||||
longLoginClient := renew.Service{}
|
||||
// qrService 保存注入的二维码协议实现。
|
||||
qrService := serverPlatformQRFake{}
|
||||
// platformDependencies 保存通过 adapter 边界校验的平台能力集合。
|
||||
platformDependencies, err := adapter.NewPlatformDependencies(mtopClient, longLoginClient, qrService)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPlatformDependencies: %v", err)
|
||||
}
|
||||
// server 保存仅含平台能力的最小 HTTP 服务测试对象。
|
||||
server := &Server{platformDependencies: platformDependencies}
|
||||
if server.mtopClient() != mtopClient {
|
||||
t.Fatalf("mtopClient 未返回显式注入客户端")
|
||||
}
|
||||
if server.longLoginClient() != longLoginClient {
|
||||
t.Fatalf("longLoginClient 未返回显式注入客户端")
|
||||
}
|
||||
if server.qrLoginService() != qrService {
|
||||
t.Fatalf("qrLoginService 未返回显式注入服务")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerPlatformAccessorsKeepLegacyTestAliases 验证兼容字段仍能替换平台能力以支撑现有测试。
|
||||
func TestServerPlatformAccessorsKeepLegacyTestAliases(t *testing.T) {
|
||||
// platformDependencies 保存生产默认平台能力,legacyMTop 和 legacyQR 保存旧测试替身。
|
||||
platformDependencies, err := adapter.NewDefaultPlatformDependencies(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDefaultPlatformDependencies: %v", err)
|
||||
}
|
||||
// legacyMTop 保存仅用于兼容测试注入的 MTOP 客户端。
|
||||
legacyMTop := adapter.NewMTOPClient()
|
||||
// legacyQR 保存仅用于兼容测试注入的二维码服务。
|
||||
legacyQR := serverPlatformQRFake{}
|
||||
// legacyLongLogin 保存仅用于兼容测试注入的长登录客户端。
|
||||
legacyLongLogin := renew.Service{}
|
||||
// server 保存同时包含新边界和旧测试字段的过渡期对象。
|
||||
server := &Server{
|
||||
platformDependencies: platformDependencies,
|
||||
MTop: legacyMTop,
|
||||
CookieRenew: legacyLongLogin,
|
||||
QRLogin: legacyQR,
|
||||
}
|
||||
if server.mtopClient() != legacyMTop || server.longLoginClient() != legacyLongLogin || server.qrLoginService() != legacyQR {
|
||||
t.Fatalf("旧测试兼容字段未优先覆盖平台访问器")
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,13 @@ func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string)
|
||||
if s == nil {
|
||||
return nil, errors.New("平台凭证读取服务未初始化")
|
||||
}
|
||||
// repository 提供不读取登录密码的平台凭证窄视图;SQL 和解密逻辑由 adapter 负责。
|
||||
repository := s.accountLoginRepositoryForServer()
|
||||
if repository == nil {
|
||||
return nil, errors.New("平台凭证 repository 未初始化")
|
||||
// service 提供消费者定义的平台凭证窄视图端口;SQL 和解密逻辑由 adapter 负责。
|
||||
service := s.platformCredentialApplication()
|
||||
if service == nil {
|
||||
return nil, errors.New("平台凭证读取服务未初始化")
|
||||
}
|
||||
// platformData 是应用 Port 返回的不含登录密码的平台运行视图。
|
||||
platformData, err := repository.LoadPlatformDetail(ctx, cookieID)
|
||||
platformData, err := service.LoadPlatformDetail(ctx, cookieID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,17 @@ import (
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// serverPlatformCredentialPortFake 返回固定的窄平台凭证视图,验证 Server 不直连数据库仓储。
|
||||
type serverPlatformCredentialPortFake struct {
|
||||
// detail 是当前测试端口返回的平台凭证视图。
|
||||
detail *accountapp.CredentialDetail
|
||||
}
|
||||
|
||||
// LoadPlatformDetail 返回测试平台凭证视图。
|
||||
func (f serverPlatformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*accountapp.CredentialDetail, error) {
|
||||
return f.detail, nil
|
||||
}
|
||||
|
||||
// TestLoadCookiePlatformDetailRequiresCredentialPort 验证平台运行时读取不会在缺少应用 Port 时直接访问 Store。
|
||||
func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) {
|
||||
// srv 是仅装配空账号登录服务的测试 Server,模拟凭证适配器缺失场景。
|
||||
@@ -19,6 +30,22 @@ func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadCookiePlatformDetailUsesCredentialApplication 验证平台运行视图通过应用 Port 读取。
|
||||
func TestLoadCookiePlatformDetailUsesCredentialApplication(t *testing.T) {
|
||||
// service 是绑定最小凭证读取端口的平台应用服务。
|
||||
service, serviceErr := accountapp.NewPlatformCredentialService(serverPlatformCredentialPortFake{detail: &accountapp.CredentialDetail{ID: "cid", UserID: 9, Value: "sid=masked"}})
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// srv 是只装配平台凭证应用服务的测试 Server。
|
||||
srv := &Server{applications: &applicationServices{platformCredentials: service}}
|
||||
// detail、loadErr 保存应用 Port 返回的平台视图及错误。
|
||||
detail, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid")
|
||||
if loadErr != nil || detail == nil || detail.ID != "cid" || detail.Value == "" {
|
||||
t.Fatalf("平台凭证视图读取异常: detail=%+v err=%v", detail, loadErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPersistMTopCookieSessionRequiresCredentialPort 验证 MTOP Cookie 会话写回通过凭证 Port 而非直接访问 Store。
|
||||
func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) {
|
||||
// srv 是仅装配空账号登录服务的测试 Server,模拟写回适配器缺失场景。
|
||||
@@ -34,3 +61,15 @@ func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) {
|
||||
t.Fatalf("缺少凭证 Port 时应报告写回错误: changed=%v handled=%v err=%v", changed, handled, persistErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformCredentialSessionPortIsAvailable 验证平台会话写回通过专用最小端口暴露。
|
||||
func TestPlatformCredentialSessionPortIsAvailable(t *testing.T) {
|
||||
// srv、cleanup 保存完整应用装配的测试 Server 及资源清理函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// sessionPort 保存仅包含 Cookie 写回能力的平台会话端口。
|
||||
sessionPort := srv.platformCredentialSessionPort()
|
||||
if sessionPort == nil {
|
||||
t.Fatal("完整应用装配应提供平台会话写回端口")
|
||||
}
|
||||
}
|
||||
@@ -62,35 +62,6 @@ func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testi
|
||||
}
|
||||
}
|
||||
|
||||
// TestCancelPublishBatchRequiresMatchingWorkerToken 负责Test取消发布批次RequiresMatching工作器令牌相关处理。
|
||||
func TestCancelPublishBatchRequiresMatchingWorkerToken(t *testing.T) {
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
srv := &Server{publishCancels: make(map[string]publishBatchWorker)}
|
||||
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
srv.registerPublishBatchCancel("batch", "current", cancel)
|
||||
|
||||
if // canceled 保存canceled,供当前处理流程使用
|
||||
canceled := srv.cancelPublishBatch("batch", "stale"); canceled {
|
||||
t.Fatal("stale worker token must not cancel current worker")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("current worker was canceled by stale token")
|
||||
default:
|
||||
}
|
||||
if // canceled 保存canceled,供当前处理流程使用
|
||||
canceled := srv.cancelPublishBatch("batch", "current"); !canceled {
|
||||
t.Fatal("matching token should cancel current worker")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
t.Fatal("matching token did not invoke cancel")
|
||||
}
|
||||
}
|
||||
|
||||
// buildImageZip 构造含一张图片的 zip 字节流。
|
||||
func buildImageZip(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
@@ -560,7 +531,7 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
|
||||
// applicationRow 保存恢复测试所需的非敏感批次明细模型。
|
||||
applicationRow := itemapp.BatchRow{ID: rows[0].ID, BatchID: rows[0].BatchID, RowNo: rows[0].RowNo, CookieID: rows[0].CookieID, Title: rows[0].Title, Description: rows[0].Description, Price: rows[0].Price, OriginalPrice: rows[0].OriginalPrice, Quantity: rows[0].Quantity, PostageMode: rows[0].PostageMode, Postage: rows[0].Postage, ImagesJSON: rows[0].ImagesJSON, CategoryJSON: rows[0].CategoryJSON, AutomationJSON: rows[0].AutomationJSON, RawJSON: rows[0].RawJSON, ItemID: rows[0].ItemID, ItemURL: rows[0].ItemURL, Status: rows[0].Status, ErrorMessage: rows[0].ErrorMessage, FailureKind: rows[0].FailureKind, WorkerToken: rows[0].WorkerToken, CreatedAt: rows[0].CreatedAt, UpdatedAt: rows[0].UpdatedAt}
|
||||
// err 保存应用层批量发布适配器的恢复结果。
|
||||
err = (serverBatchPublisher{server: srv, remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2")
|
||||
err = (serverBatchPublisher{remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2")
|
||||
if err != nil {
|
||||
t.Fatalf("resume local persistence: %v", err)
|
||||
}
|
||||
@@ -594,7 +565,10 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.recoverPublishBatchesOnce(ctx)
|
||||
// err 保存应用层批量恢复扫描的错误。
|
||||
if err := srv.applications.itemBatchCoordinator.RunRecovery(ctx); err != nil {
|
||||
t.Fatalf("批量恢复扫描: %v", err)
|
||||
}
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
"xianyu-go/internal/auth"
|
||||
)
|
||||
|
||||
@@ -37,8 +38,14 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
|
||||
// generateCtx、cancel 保存generateCtx、cancel,供当前处理流程使用
|
||||
generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout)
|
||||
defer cancel()
|
||||
// qrService 是通过显式平台依赖边界取得的二维码服务;为空时拒绝执行平台调用。
|
||||
qrService := s.qrLoginService()
|
||||
if qrService == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
|
||||
return
|
||||
}
|
||||
// sessionID、qrCodeURL、err 保存会话ID、qrCodeURL、err,供当前处理流程使用
|
||||
sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(generateCtx)
|
||||
sessionID, qrCodeURL, err := qrService.GenerateQRCode(generateCtx)
|
||||
if err != nil {
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := "生成二维码失败: " + err.Error()
|
||||
@@ -58,9 +65,13 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
|
||||
message, "")
|
||||
return
|
||||
}
|
||||
s.qrMu.Lock()
|
||||
s.qrOwners[sessionID] = qrLoginOwner{UserID: sess.UserID, CreatedAt: time.Now().UTC()}
|
||||
s.qrMu.Unlock()
|
||||
// qrSessions 保存扫码会话所有权;平台二维码服务只负责平台会话本身。
|
||||
qrSessions := s.accountLoginApplication().qrSessions
|
||||
if qrSessions == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化")
|
||||
return
|
||||
}
|
||||
qrSessions.Register(sessionID, sess.UserID, time.Now().UTC())
|
||||
writeJSON(w, http.StatusOK, qrLoginGenerateResponse{
|
||||
Success: true, SessionID: sessionID, QRCodeURL: qrCodeURL,
|
||||
// 生成成功响应只暴露会话标识和二维码地址。
|
||||
@@ -79,8 +90,14 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireQRSessionOwner(w, r, sessionID) {
|
||||
return
|
||||
}
|
||||
// qrService 是已完成平台依赖校验的二维码服务。
|
||||
qrService := s.qrLoginService()
|
||||
if qrService == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
|
||||
return
|
||||
}
|
||||
// result 保存结果,供当前处理流程使用
|
||||
result := publicQRStatus(s.QRLogin.GetSessionStatus(sessionID))
|
||||
result := publicQRStatus(qrService.GetSessionStatus(sessionID))
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
@@ -95,8 +112,14 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
|
||||
if !s.requireQRSessionOwner(w, r, sessionID) {
|
||||
return
|
||||
}
|
||||
// qrService 是已完成平台依赖校验的二维码服务。
|
||||
qrService := s.qrLoginService()
|
||||
if qrService == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
|
||||
return
|
||||
}
|
||||
// result 保存结果,供当前处理流程使用
|
||||
result := cloneQRStatus(s.QRLogin.GetSessionStatus(sessionID))
|
||||
result := cloneQRStatus(qrService.GetSessionStatus(sessionID))
|
||||
if qrStatus(result) != "success" {
|
||||
writeJSON(w, http.StatusOK, publicQRStatus(result))
|
||||
return
|
||||
@@ -136,8 +159,14 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
if !s.requireQRSessionOwner(w, r, sessionID) {
|
||||
return
|
||||
}
|
||||
// qrService 是已完成平台依赖校验的二维码服务。
|
||||
qrService := s.qrLoginService()
|
||||
if qrService == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
|
||||
return
|
||||
}
|
||||
// cookies、unb、err 保存cookies、unb、err,供当前处理流程使用
|
||||
cookies, unb, err := s.QRLogin.CompleteVerification(r.Context(), sessionID)
|
||||
cookies, unb, err := qrService.CompleteVerification(r.Context(), sessionID)
|
||||
if err != nil {
|
||||
s.Logger.Error("验证完成处理失败", "err", err)
|
||||
writeErrCode(
|
||||
@@ -146,10 +175,8 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
err.Error(), "")
|
||||
return
|
||||
}
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
TargetAccountID string `json:"target_account_id"`
|
||||
}
|
||||
// req 保存具名扫码验证完成请求。
|
||||
var req qrVerificationRequestDTO
|
||||
if r.Body != nil && r.ContentLength != 0 {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
@@ -181,7 +208,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
"unb": unb,
|
||||
}
|
||||
if // current 保存current,供当前处理流程使用
|
||||
current := s.QRLogin.GetSessionStatus(sessionID); current != nil {
|
||||
current := qrService.GetSessionStatus(sessionID); current != nil {
|
||||
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
|
||||
snapshot, ok := current["cookie_snapshot"]; ok {
|
||||
result["cookie_snapshot"] = snapshot
|
||||
@@ -212,24 +239,20 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return false
|
||||
}
|
||||
s.qrMu.Lock()
|
||||
// owner、ok 保存owner、ok,供当前处理流程使用
|
||||
owner, ok := s.qrOwners[sessionID]
|
||||
// expired 保存expired,供当前处理流程使用
|
||||
expired := ok && owner.CreatedAt.Before(time.Now().UTC().Add(-30*time.Minute))
|
||||
if expired {
|
||||
delete(s.qrOwners, sessionID)
|
||||
delete(s.qrPersisted, sessionID)
|
||||
s.qrPersistLocks.Delete(sessionID)
|
||||
// qrSessions 负责所有权、过期判断和幂等状态清理,HTTP 层不再持有可变会话表。
|
||||
qrSessions := s.accountLoginApplication().qrSessions
|
||||
if qrSessions == nil {
|
||||
writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化")
|
||||
return false
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
if expired {
|
||||
if // cleaner、cleanable 保存cleaner、cleanable,供当前处理流程使用
|
||||
cleaner, cleanable := s.QRLogin.(interface{ DeleteSession(string) }); cleanable {
|
||||
cleaner.DeleteSession(sessionID)
|
||||
// err 保存扫码会话所有权校验结果。
|
||||
if err := qrSessions.Authorize(sessionID, sess.UserID); err != nil {
|
||||
if errors.Is(err, accountapp.ErrQRLoginSessionNotFound) {
|
||||
// cleaner、cleanable 分别表示平台会话清理器及其接口是否可用。
|
||||
if cleaner, cleanable := s.qrLoginService().(interface{ DeleteSession(string) }); cleanable {
|
||||
cleaner.DeleteSession(sessionID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ok || expired || owner.UserID != sess.UserID {
|
||||
writeErr(w, http.StatusNotFound, "扫码会话不存在或已过期")
|
||||
return false
|
||||
}
|
||||
@@ -238,23 +261,15 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
|
||||
|
||||
// cleanupQRLoginSessions 负责cleanupQR登录Sessions相关处理。
|
||||
func (s *Server) cleanupQRLoginSessions() {
|
||||
// cutoff 保存cutoff,供当前处理流程使用
|
||||
cutoff := time.Now().UTC().Add(-30 * time.Minute)
|
||||
// expired 保存expired,供当前处理流程使用
|
||||
expired := make([]string, 0)
|
||||
s.qrMu.Lock()
|
||||
// id、owner 表示当前遍历过程中的id、owner
|
||||
for id, owner := range s.qrOwners {
|
||||
if owner.CreatedAt.Before(cutoff) {
|
||||
delete(s.qrOwners, id)
|
||||
delete(s.qrPersisted, id)
|
||||
s.qrPersistLocks.Delete(id)
|
||||
expired = append(expired, id)
|
||||
}
|
||||
// qrSessions 提供应用层扫码会话过期清理能力。
|
||||
qrSessions := s.accountLoginApplication().qrSessions
|
||||
if qrSessions == nil {
|
||||
return
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
// expired 保存应用层报告的过期扫码会话标识。
|
||||
expired := qrSessions.Cleanup(time.Now().UTC())
|
||||
if // cleaner、ok 保存cleaner、ok,供当前处理流程使用
|
||||
cleaner, ok := s.QRLogin.(interface{ DeleteSession(string) }); ok {
|
||||
cleaner, ok := s.qrLoginService().(interface{ DeleteSession(string) }); ok {
|
||||
// id 表示当前遍历过程中的标识
|
||||
for _, id := range expired {
|
||||
cleaner.DeleteSession(id)
|
||||
@@ -277,11 +292,29 @@ func cloneQRStatus(src map[string]any) map[string]any {
|
||||
// 永远不进入前端、浏览器日志或代理响应。
|
||||
// publicQRStatus 负责publicQR状态相关处理。
|
||||
func publicQRStatus(src map[string]any) qrLoginStatusResponse {
|
||||
// dst 保存dst,供当前处理流程使用
|
||||
dst := qrLoginStatusResponse(cloneQRStatus(src))
|
||||
delete(dst, "cookies")
|
||||
delete(dst, "cookie_snapshot")
|
||||
return dst
|
||||
// status 保存允许传输到浏览器的扫码状态;Cookie 和快照字段刻意不映射。
|
||||
status := qrLoginStatusResponse{Status: qrStatus(src)}
|
||||
// success 表示上游是否报告扫码流程成功;ok 表示字段类型确实为布尔值。
|
||||
if success, ok := src["success"].(bool); ok {
|
||||
status.Success = success
|
||||
}
|
||||
// message 保存上游返回的用户提示文本;ok 表示字段类型确实为字符串。
|
||||
if message, ok := src["message"].(string); ok {
|
||||
status.Message = message
|
||||
}
|
||||
// sessionID 保存扫码会话标识;ok 表示字段类型确实为字符串。
|
||||
if sessionID, ok := src["session_id"].(string); ok {
|
||||
status.SessionID = sessionID
|
||||
}
|
||||
// accountID 保存扫码成功后关联的本地账号标识;ok 表示字段类型确实为字符串。
|
||||
if accountID, ok := src["account_id"].(string); ok {
|
||||
status.AccountID = accountID
|
||||
}
|
||||
// isNew 表示是否新建本地账号;ok 表示字段类型确实为布尔值。
|
||||
if isNew, ok := src["is_new_account"].(bool); ok {
|
||||
status.IsNewAccount = isNew
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// qrStatus 负责qr状态相关处理。
|
||||
|
||||
@@ -195,7 +195,7 @@ func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
|
||||
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
|
||||
srv.qrOwners["expired-session"] = qrLoginOwner{UserID: admin.ID, CreatedAt: time.Now().UTC().Add(-31 * time.Minute)}
|
||||
srv.accountLoginApplication().qrSessions.Register("expired-session", admin.ID, time.Now().UTC().Add(-31*time.Minute))
|
||||
// h 保存h,供当前处理流程使用
|
||||
h := srv.Router()
|
||||
// cookie 保存登录凭证,供当前处理流程使用
|
||||
@@ -265,9 +265,7 @@ func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByUsername admin: %v", err)
|
||||
}
|
||||
srv.qrMu.Lock()
|
||||
srv.qrOwners[sessionID] = qrLoginOwner{UserID: admin.ID, CreatedAt: time.Now().UTC()}
|
||||
srv.qrMu.Unlock()
|
||||
srv.accountLoginApplication().qrSessions.Register(sessionID, admin.ID, time.Now().UTC())
|
||||
}
|
||||
|
||||
// TestQRLoginStatusPersistsSuccessIdempotently 负责TestQR登录状态PersistsSuccessIdempotently相关处理。
|
||||
|
||||
+78
-35
@@ -75,32 +75,6 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishWorkerTrackingWaitsForCompletion 负责Test发布工作器TrackingWaitsForCompletion相关处理。
|
||||
func TestPublishWorkerTrackingWaitsForCompletion(t *testing.T) {
|
||||
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// doneWorker 保存done工作器,供当前处理流程使用
|
||||
doneWorker := srv.beginWorker()
|
||||
// waited 保存waited,供当前处理流程使用
|
||||
waited := make(chan struct{})
|
||||
go func() {
|
||||
srv.waitForWorkers(time.Second)
|
||||
close(waited)
|
||||
}()
|
||||
select {
|
||||
case <-waited:
|
||||
t.Fatal("wait returned while worker was still active")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
doneWorker()
|
||||
select {
|
||||
case <-waited:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("wait did not return after worker completed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishRecoveryLifecycleStopsBeforeWorkerWait 负责Test发布RecoveryLifecycleStopsBefore工作器Wait相关处理。
|
||||
func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
|
||||
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
|
||||
@@ -108,12 +82,15 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
|
||||
defer cleanup()
|
||||
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
srv.StartPublishBatchRecovery(ctx)
|
||||
// err 表示测试批量恢复组件启动失败的原因。
|
||||
if err := srv.applications.itemBatchCoordinator.StartRecovery(ctx); err != nil {
|
||||
t.Fatalf("启动批量发布恢复扫描器: %v", err)
|
||||
}
|
||||
cancel()
|
||||
// done 保存done,供当前处理流程使用
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
srv.WaitForBackground()
|
||||
srv.applications.itemBatchCoordinator.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
@@ -126,7 +103,7 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
|
||||
// TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。
|
||||
func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
|
||||
// err 是缺少基础设施容器时的构造校验错误。
|
||||
if _, err := New(nil, nil, nil, "", ":0", nil, nil, nil); err == nil {
|
||||
if _, err := New(nil, nil, "", ":0", nil, nil, nil); err == nil {
|
||||
t.Fatal("缺少基础设施容器时应返回构造错误")
|
||||
}
|
||||
// srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。
|
||||
@@ -135,17 +112,83 @@ func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
|
||||
if srv == nil {
|
||||
t.Fatal("测试服务不应为空")
|
||||
}
|
||||
// dependencies 保存缺少 Manager 校验时复用的基础设施容器。
|
||||
dependencies, dependencyErr := adapter.NewDependencies(store)
|
||||
if dependencyErr != nil {
|
||||
t.Fatalf("NewDependencies: %v", dependencyErr)
|
||||
}
|
||||
// authentication 保存构造校验需要的会话中间件依赖。
|
||||
authentication := &auth.Service{Store: store}
|
||||
// err 是缺少 Manager 时的构造校验错误。
|
||||
if _, err := New(dependencies, authentication, nil, "", ":0", nil, nil, nil); err == nil {
|
||||
if _, err := New(authentication, nil, "", ":0", nil, nil, nil); err == nil {
|
||||
t.Fatal("缺少 account.Manager 时应返回构造错误")
|
||||
}
|
||||
// err 是缺少订单专用装配能力时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil); err == nil {
|
||||
t.Fatal("缺少订单专用依赖时应返回构造错误")
|
||||
}
|
||||
// orderDependencies 保存账号依赖缺失测试所需的合法订单装配能力。
|
||||
orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store)
|
||||
if orderDependencyErr != nil {
|
||||
t.Fatalf("NewOrderDependencies: %v", orderDependencyErr)
|
||||
}
|
||||
// err 是缺少账号专用装配能力时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies)); err == nil {
|
||||
t.Fatal("缺少账号专用依赖时应返回构造错误")
|
||||
}
|
||||
// accountDependencies 保存账号与订单依赖均合法时的商品依赖缺失测试输入。
|
||||
accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store)
|
||||
if accountDependencyErr != nil {
|
||||
t.Fatalf("NewAccountDependencies: %v", accountDependencyErr)
|
||||
}
|
||||
// err 是缺少商品专用装配能力时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies)); err == nil {
|
||||
t.Fatal("缺少商品专用依赖时应返回构造错误")
|
||||
}
|
||||
// err 是订单、账号和商品依赖齐全但平台客户端缺失时的构造校验错误。
|
||||
itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store)
|
||||
if itemDependencyErr != nil {
|
||||
t.Fatalf("NewItemDependencies: %v", itemDependencyErr)
|
||||
}
|
||||
// platformDependencies 保存依赖缺失分支测试使用的显式平台能力。
|
||||
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
|
||||
if platformDependencyErr != nil {
|
||||
t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr)
|
||||
}
|
||||
// chatDependencies 保存平台缺失校验所需的聊天专用依赖。
|
||||
chatDependencies := adapter.NewChatDependencies(store)
|
||||
// systemDependencies 保存平台缺失校验所需的系统专用依赖。
|
||||
systemDependencies := adapter.NewSystemDependencies(store)
|
||||
// automationDependencies 保存平台缺失校验所需的自动化专用依赖及构造错误。
|
||||
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
|
||||
if automationDependencyErr != nil {
|
||||
t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr)
|
||||
}
|
||||
// miscDependencies 保存平台缺失校验所需的杂项专用依赖及构造错误。
|
||||
miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store)
|
||||
if miscDependencyErr != nil {
|
||||
t.Fatalf("NewMiscDependencies: %v", miscDependencyErr)
|
||||
}
|
||||
// adminSettingsDependencies 保存平台缺失校验所需的管理员设置依赖。
|
||||
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
|
||||
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
|
||||
t.Fatal("显式 Server 依赖构造失败")
|
||||
}
|
||||
// err 是聊天或系统等显式依赖缺失时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies)); err == nil {
|
||||
t.Fatal("缺少聊天或系统专用依赖时应返回构造错误")
|
||||
}
|
||||
// err 是缺少平台依赖注入时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies)); err == nil {
|
||||
t.Fatal("缺少平台依赖时应返回构造错误")
|
||||
}
|
||||
// err 是缺少自动化专用依赖时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
|
||||
t.Fatal("缺少自动化专用依赖时应返回构造错误")
|
||||
}
|
||||
// err 是缺少杂项专用依赖时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
|
||||
t.Fatal("缺少杂项专用依赖时应返回构造错误")
|
||||
}
|
||||
// err 是缺少管理员设置专用依赖时的构造校验错误。
|
||||
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
|
||||
t.Fatal("缺少管理员设置专用依赖时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerStartStopIsIdempotentAndWaitsForWorkers 验证 Start/Stop 可重复调用且 Stop 等待 worker。
|
||||
|
||||
+296
-183
@@ -21,12 +21,14 @@ import (
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/adapter"
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
lifecycleapp "xianyu-go/internal/application/lifecycle"
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/logging"
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/reconciliation"
|
||||
appversion "xianyu-go/internal/version"
|
||||
"xianyu-go/internal/webui"
|
||||
)
|
||||
@@ -42,21 +44,55 @@ type qrLoginPersistence struct {
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// qrLoginOwner 保存qr登录所有者,供当前处理流程使用
|
||||
type qrLoginOwner struct {
|
||||
UserID int64
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// publishBatchWorker 保存发布批次工作器,供当前处理流程使用
|
||||
type publishBatchWorker struct {
|
||||
token string
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// ServerOption 是 Server 构造阶段应用可选依赖的配置函数。
|
||||
type ServerOption func(*Server)
|
||||
|
||||
// orderDependencyFactory 是订单装配所需的最小能力集合;Server 不持有通用 Store 工厂。
|
||||
type orderDependencyFactory interface {
|
||||
// NewOrderRepository 创建订单读写仓储。
|
||||
NewOrderRepository() *adapter.OrderRepository
|
||||
// NewOrderReconciliationRepository 创建订单补偿记录仓储。
|
||||
NewOrderReconciliationRepository() *adapter.OrderReconciliationRepository
|
||||
// NewOrderRuntime 创建订单平台运行时适配器。
|
||||
NewOrderRuntime(adapter.OrderRuntimeHooks, orderapp.ReconciliationRecorder, *slog.Logger) *adapter.OrderRuntime
|
||||
// NewOrderRefreshJobRepository 创建订单刷新任务仓储。
|
||||
NewOrderRefreshJobRepository() orderapp.RefreshJobRepository
|
||||
}
|
||||
|
||||
// accountDependencyFactory 是账号应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。
|
||||
type accountDependencyFactory interface {
|
||||
// NewAccountLoginRepository 创建账号凭证与资料仓储。
|
||||
NewAccountLoginRepository() *adapter.AccountLoginRepository
|
||||
// NewAccountSettingsRepository 创建账号设置仓储。
|
||||
NewAccountSettingsRepository() *adapter.AccountSettingsRepository
|
||||
// NewAccountSummaryRepository 创建账号摘要仓储。
|
||||
NewAccountSummaryRepository() *adapter.AccountSummaryRepository
|
||||
// NewQRLoginRepository 创建扫码登录凭证端口。
|
||||
NewQRLoginRepository() accountapp.QRLoginRepository
|
||||
// NewAuthenticationRepository 创建用户认证仓储。
|
||||
NewAuthenticationRepository() *adapter.AuthenticationRepository
|
||||
// NewAccountLoginAuditRepository 创建账号登录审计仓储。
|
||||
NewAccountLoginAuditRepository() *adapter.AccountLoginAuditRepository
|
||||
}
|
||||
|
||||
// itemDependencyFactory 是商品应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。
|
||||
type itemDependencyFactory interface {
|
||||
// NewItemBatchRepository 创建批量发布状态仓储。
|
||||
NewItemBatchRepository() *adapter.ItemBatchRepository
|
||||
// NewItemBatchPreviewPort 创建批量预检端口。
|
||||
NewItemBatchPreviewPort() *adapter.ItemBatchPreviewPort
|
||||
// NewItemBatchPublishPort 创建批量远端发布端口。
|
||||
NewItemBatchPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error), adapter.ReadPublishImageFile, adapter.DownloadPublishImageURL) *adapter.ItemBatchPublishPort
|
||||
// NewItemPublishPort 创建单商品发布端口。
|
||||
NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemPublishPort
|
||||
// NewItemPublishRepository 创建单商品发布结果仓储。
|
||||
NewItemPublishRepository() *adapter.ItemPublishRepository
|
||||
// NewItemCatalogRepository 创建商品目录仓储。
|
||||
NewItemCatalogRepository() *adapter.ItemCatalogRepository
|
||||
// NewItemSyncRepository 创建商品同步端口。
|
||||
NewItemSyncRepository(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemSyncRepository
|
||||
}
|
||||
|
||||
// databaseHealth 定义健康检查需要的最小数据库连通性能力。
|
||||
type databaseHealth interface {
|
||||
// Ping 在调用方 Context 内探测数据库连接是否可用。
|
||||
@@ -67,34 +103,44 @@ type databaseHealth interface {
|
||||
// 不再允许外部直接改字段,避免运行时被替换成 nil。
|
||||
// Server 保存Server,供当前处理流程使用
|
||||
type Server struct {
|
||||
// dependencies 提供数据库和平台适配器工厂;底层 Store 不进入 Server 业务字段。
|
||||
dependencies *adapter.Dependencies
|
||||
Auth *auth.Service
|
||||
Manager *account.Manager
|
||||
automation *automation.Center
|
||||
notifier *notify.Notifier
|
||||
chat *chat.Service
|
||||
MTop adapter.MTOPClient
|
||||
CookieRenew adapter.LongLoginClient
|
||||
QRLogin qrLoginService
|
||||
Logger *slog.Logger
|
||||
WebDir string // 前端静态资源目录(含 index.html)
|
||||
Addr string
|
||||
// orderDependencies 保存订单应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
|
||||
orderDependencies orderDependencyFactory
|
||||
// accountDependencies 保存账号应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
|
||||
accountDependencies accountDependencyFactory
|
||||
// itemDependencies 保存商品应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
|
||||
itemDependencies itemDependencyFactory
|
||||
// chatDependencies 保存聊天应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
|
||||
chatDependencies *adapter.ChatDependencies
|
||||
// systemDependencies 保存健康检查与补偿扫描的显式装配能力。
|
||||
systemDependencies *adapter.SystemDependencies
|
||||
// automationDependencies 保存自动化、默认回复和关键词的显式装配能力。
|
||||
automationDependencies *adapter.AutomationDependencies
|
||||
// miscDependencies 保存通知、分析和卡券的显式装配能力。
|
||||
miscDependencies *adapter.MiscDependencies
|
||||
// adminSettingsDependencies 保存管理员与系统设置的显式装配能力。
|
||||
adminSettingsDependencies *adapter.AdminSettingsDependencies
|
||||
Auth *auth.Service
|
||||
Manager *account.Manager
|
||||
automation *automation.Center
|
||||
notifier *notify.Notifier
|
||||
chat *chat.Service
|
||||
// platformDependencies 保存构造阶段校验通过的平台能力;生产调用必须通过下方访问器读取。
|
||||
platformDependencies *adapter.PlatformDependencies
|
||||
// MTop 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
|
||||
MTop adapter.MTOPClient
|
||||
// CookieRenew 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
|
||||
CookieRenew adapter.LongLoginClient
|
||||
// QRLogin 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
|
||||
QRLogin qrLoginService
|
||||
Logger *slog.Logger
|
||||
WebDir string // 前端静态资源目录(含 index.html)
|
||||
Addr string
|
||||
// applications 保存统一装配的应用服务实例。
|
||||
applications *applicationServices
|
||||
// reconciliation 负责恢复外部发货成功但本地订单状态未完成的记录。
|
||||
reconciliation *reconciliation.Service
|
||||
// transactionRepository 提供统一事务执行所需的最小持久化能力。
|
||||
transactionRepository *adapter.TransactionRepository
|
||||
// applicationLifecycle 保存由 cmd 拥有的应用生命周期协调器;Server 只读取其共享 Context。
|
||||
applicationLifecycle *lifecycleapp.Coordinator
|
||||
// databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。
|
||||
databaseHealth databaseHealth
|
||||
publishMu sync.Mutex
|
||||
publishCancels map[string]publishBatchWorker
|
||||
orderRefreshMu sync.Mutex
|
||||
orderRefreshCancels map[string]orderRefreshWorker
|
||||
workerMu sync.Mutex
|
||||
workerCount int
|
||||
workersDone chan struct{}
|
||||
databaseHealth databaseHealth
|
||||
// backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。
|
||||
backgroundMu sync.Mutex
|
||||
backgroundCount int
|
||||
@@ -102,22 +148,14 @@ type Server struct {
|
||||
// taskRegistryMu 保护后台任务注册表的惰性初始化,避免测试构造的零值 Server 产生数据竞争。
|
||||
taskRegistryMu sync.Mutex
|
||||
// taskRegistry 保存 Server 自有后台任务的生命周期状态,不持久化业务数据或敏感凭证。
|
||||
taskRegistry *taskRegistry
|
||||
lifecycleMu sync.RWMutex
|
||||
lifecycleCtx context.Context
|
||||
lifecycleCancel context.CancelFunc
|
||||
httpServer *http.Server
|
||||
httpDone chan struct{}
|
||||
httpErr error
|
||||
started bool
|
||||
stopped bool
|
||||
taskRegistry *taskRegistry
|
||||
lifecycleMu sync.RWMutex
|
||||
httpServer *http.Server
|
||||
httpDone chan struct{}
|
||||
httpErr error
|
||||
started bool
|
||||
stopped bool
|
||||
|
||||
qrMu sync.Mutex
|
||||
qrPersisted map[string]qrLoginPersistence
|
||||
qrOwners map[string]qrLoginOwner
|
||||
// qrPersistLocks 按扫码会话串行化持久化,避免持有全局 qrMu 执行数据库、
|
||||
// 资料刷新和账号重启等慢操作。
|
||||
qrPersistLocks sync.Map
|
||||
loginLimiter *loginFailureLimiter
|
||||
initializationMu sync.Mutex
|
||||
}
|
||||
@@ -130,13 +168,101 @@ func WithChatService(service *chat.Service) ServerOption {
|
||||
}
|
||||
}
|
||||
|
||||
// New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入
|
||||
// (创建顺序:adapter → manager → automation → notifier → server)。
|
||||
// New 负责New相关处理。
|
||||
func New(dependencies *adapter.Dependencies, authentication *auth.Service, manager *account.Manager, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
|
||||
if dependencies == nil {
|
||||
return nil, fmt.Errorf("server 依赖基础设施容器不能为空")
|
||||
// WithOrderDependencies 注入订单应用服务所需的专用适配器工厂。
|
||||
func WithOrderDependencies(dependencies *adapter.OrderDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入订单专用依赖的 HTTP 服务实例。
|
||||
if dependencies == nil {
|
||||
server.orderDependencies = nil
|
||||
return
|
||||
}
|
||||
server.orderDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithAccountDependencies 注入账号应用服务所需的专用适配器工厂。
|
||||
func WithAccountDependencies(dependencies *adapter.AccountDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入账号专用依赖的 HTTP 服务实例。
|
||||
if dependencies == nil {
|
||||
server.accountDependencies = nil
|
||||
return
|
||||
}
|
||||
server.accountDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithItemDependencies 注入商品应用服务所需的专用适配器工厂。
|
||||
func WithItemDependencies(dependencies *adapter.ItemDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入商品专用依赖的 HTTP 服务实例。
|
||||
if dependencies == nil {
|
||||
server.itemDependencies = nil
|
||||
return
|
||||
}
|
||||
server.itemDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithChatDependencies 注入聊天应用服务所需的专用适配器工厂。
|
||||
func WithChatDependencies(dependencies *adapter.ChatDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入聊天专用依赖的 HTTP 服务实例。
|
||||
server.chatDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithSystemDependencies 注入健康检查与订单补偿扫描所需的专用适配器工厂。
|
||||
func WithSystemDependencies(dependencies *adapter.SystemDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入系统专用依赖的 HTTP 服务实例。
|
||||
server.systemDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithAutomationDependencies 注入自动化领域所需的专用适配器工厂。
|
||||
func WithAutomationDependencies(dependencies *adapter.AutomationDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入自动化专用依赖的 HTTP 服务实例。
|
||||
server.automationDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithMiscDependencies 注入通知、分析和卡券领域所需的专用适配器工厂。
|
||||
func WithMiscDependencies(dependencies *adapter.MiscDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入杂项领域依赖的 HTTP 服务实例。
|
||||
server.miscDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithAdminSettingsDependencies 注入管理员与系统设置所需的专用适配器工厂。
|
||||
func WithAdminSettingsDependencies(dependencies *adapter.AdminSettingsDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入管理员设置依赖的 HTTP 服务实例。
|
||||
server.adminSettingsDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithPlatformDependencies 注入 MTOP、长登录和二维码服务组成的平台能力边界。
|
||||
func WithPlatformDependencies(dependencies *adapter.PlatformDependencies) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入平台依赖的 HTTP 服务实例。
|
||||
server.platformDependencies = dependencies
|
||||
}
|
||||
}
|
||||
|
||||
// WithApplicationLifecycle 注入由进程装配层拥有的应用生命周期协调器。
|
||||
func WithApplicationLifecycle(coordinator *lifecycleapp.Coordinator) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中需要读取应用生命周期 Context 的 HTTP 服务实例。
|
||||
server.applicationLifecycle = coordinator
|
||||
}
|
||||
}
|
||||
|
||||
// New 构造并校验 HTTP 服务所需依赖;订单、账号、商品、系统和平台能力必须由显式依赖边界注入。
|
||||
// autoCenter/notifier 由调用方完成创建后注入,构造顺序为 adapter → manager → automation → notifier → server。
|
||||
func New(authentication *auth.Service, manager *account.Manager, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
|
||||
if authentication == nil {
|
||||
return nil, fmt.Errorf("server 依赖认证服务不能为空")
|
||||
}
|
||||
@@ -148,27 +274,16 @@ func New(dependencies *adapter.Dependencies, authentication *auth.Service, manag
|
||||
}
|
||||
// server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。
|
||||
server := &Server{
|
||||
dependencies: dependencies,
|
||||
Auth: authentication,
|
||||
Manager: manager,
|
||||
automation: autoCenter,
|
||||
notifier: notifier,
|
||||
MTop: adapter.NewMTOPClient(),
|
||||
CookieRenew: adapter.NewLongLoginClient(),
|
||||
QRLogin: adapter.NewQRLoginService(logger),
|
||||
Logger: logger,
|
||||
WebDir: webDir,
|
||||
Addr: addr,
|
||||
|
||||
publishCancels: make(map[string]publishBatchWorker),
|
||||
orderRefreshCancels: make(map[string]orderRefreshWorker),
|
||||
workersDone: closedSignal(),
|
||||
lifecycleCtx: context.Background(),
|
||||
qrPersisted: make(map[string]qrLoginPersistence),
|
||||
qrOwners: make(map[string]qrLoginOwner),
|
||||
loginLimiter: newLoginFailureLimiter(),
|
||||
taskRegistry: newTaskRegistry(),
|
||||
backgroundDone: closedSignal(),
|
||||
Auth: authentication,
|
||||
Manager: manager,
|
||||
automation: autoCenter,
|
||||
notifier: notifier,
|
||||
Logger: logger,
|
||||
WebDir: webDir,
|
||||
Addr: addr,
|
||||
loginLimiter: newLoginFailureLimiter(),
|
||||
taskRegistry: newTaskRegistry(),
|
||||
backgroundDone: closedSignal(),
|
||||
}
|
||||
// option 表示当前遍历过程中的option
|
||||
for _, option := range options {
|
||||
@@ -177,35 +292,98 @@ func New(dependencies *adapter.Dependencies, authentication *auth.Service, manag
|
||||
option(server)
|
||||
}
|
||||
}
|
||||
if server.orderDependencies == nil {
|
||||
return nil, fmt.Errorf("server 订单专用依赖不能为空")
|
||||
}
|
||||
if server.accountDependencies == nil {
|
||||
return nil, fmt.Errorf("server 账号专用依赖不能为空")
|
||||
}
|
||||
if server.itemDependencies == nil {
|
||||
return nil, fmt.Errorf("server 商品专用依赖不能为空")
|
||||
}
|
||||
if server.chatDependencies == nil {
|
||||
return nil, fmt.Errorf("server 聊天专用依赖不能为空")
|
||||
}
|
||||
if server.systemDependencies == nil {
|
||||
return nil, fmt.Errorf("server 系统专用依赖不能为空")
|
||||
}
|
||||
if server.platformDependencies == nil {
|
||||
return nil, fmt.Errorf("server 平台依赖不能为空")
|
||||
}
|
||||
if server.automationDependencies == nil {
|
||||
return nil, fmt.Errorf("server 自动化依赖不能为空")
|
||||
}
|
||||
if server.miscDependencies == nil {
|
||||
return nil, fmt.Errorf("server 通知、分析和卡券依赖不能为空")
|
||||
}
|
||||
if server.adminSettingsDependencies == nil {
|
||||
return nil, fmt.Errorf("server 管理员与设置依赖不能为空")
|
||||
}
|
||||
server.applications = newApplicationServices(server)
|
||||
server.transactionRepository = dependencies.NewTransactionRepository()
|
||||
server.databaseHealth = dependencies.NewDatabaseHealth()
|
||||
server.reconciliation = dependencies.NewReconciliationService(logger)
|
||||
server.databaseHealth = server.systemDependencies.NewDatabaseHealth()
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
|
||||
// mtopClient 返回构造阶段校验的平台 MTOP 客户端;零值 Server 返回 nil,避免隐式创建依赖。
|
||||
func (s *Server) mtopClient() adapter.MTOPClient {
|
||||
if s.MTop != nil {
|
||||
return s.MTop
|
||||
}
|
||||
return adapter.NewMTOPClient()
|
||||
if s.platformDependencies != nil && s.platformDependencies.MTOPClient() != nil {
|
||||
return s.platformDependencies.MTOPClient()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。
|
||||
// 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。
|
||||
// recoverExpiredMTOPSession 负责recoverExpiredMTOP会话相关处理。
|
||||
// longLoginClient 返回构造阶段注入的长登录客户端;旧公开字段仅用于兼容现有测试替身。
|
||||
func (s *Server) longLoginClient() adapter.LongLoginClient {
|
||||
if s.CookieRenew != nil {
|
||||
return s.CookieRenew
|
||||
}
|
||||
if s.platformDependencies != nil && s.platformDependencies.LongLoginClient() != nil {
|
||||
return s.platformDependencies.LongLoginClient()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// qrLoginService 返回构造阶段注入的二维码服务;旧公开字段仅用于兼容现有测试替身。
|
||||
func (s *Server) qrLoginService() qrLoginService {
|
||||
if s.QRLogin != nil {
|
||||
return s.QRLogin
|
||||
}
|
||||
if s.platformDependencies != nil && s.platformDependencies.QRLoginService() != nil {
|
||||
return s.platformDependencies.QRLoginService()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sessionRecoveryCallback 返回平台会话失效的统一适配回调。
|
||||
// 适配器负责错误分类和日志,账号运行时应用端口负责恢复;调用方不得跨凭证锁执行外部 I/O。
|
||||
func (s *Server) sessionRecoveryCallback() adapter.SessionRecoveryHandler {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return adapter.NewSessionRecoveryHandler(s.Logger, func(ctx context.Context, cookieID string) bool {
|
||||
// runtime 保存账号运行时应用服务;恢复由应用端口编排而非 HTTP 层直接调用 Manager。
|
||||
runtime := s.accountRuntimeApplication()
|
||||
return runtime != nil && runtime.RecoverExpiredCredential(ctx, cookieID)
|
||||
})
|
||||
}
|
||||
|
||||
// recoverExpiredMTOPSession 保留旧测试入口并委托统一 Session 恢复适配回调。
|
||||
// 新生产调用应直接注入 sessionRecoveryCallback,避免把 Server 方法传入基础设施适配器。
|
||||
func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool {
|
||||
if !adapter.IsSessionExpiredError(err) {
|
||||
return false
|
||||
}
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("MTOP API 检测到 Session 过期,停止业务请求并开始即时续期", "account", cookieID, "err", err)
|
||||
}
|
||||
if s.Manager == nil {
|
||||
return false
|
||||
}
|
||||
return s.Manager.RecoverExpiredCredential(ctx, cookieID)
|
||||
// recovery 保存统一的错误分类、日志和运行时恢复回调。
|
||||
recovery := s.sessionRecoveryCallback()
|
||||
return recovery != nil && recovery(ctx, cookieID, err)
|
||||
}
|
||||
|
||||
// recoverExpiredSession 触发已注入的平台会话恢复回调,供 HTTP transport 处理应用层平台错误。
|
||||
// 该方法不读取凭证、不调用 Manager,也不在凭证锁内执行外部 I/O。
|
||||
func (s *Server) recoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
|
||||
// recovery 保存统一的错误分类、日志和运行时恢复回调。
|
||||
recovery := s.sessionRecoveryCallback()
|
||||
return recovery != nil && recovery(ctx, cookieID, err)
|
||||
}
|
||||
|
||||
// Router 构建完整路由树。
|
||||
@@ -483,12 +661,6 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
WriteTimeout: 2 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
// lifecycleCtx 是 Server 内部可取消的生命周期上下文。
|
||||
// lifecycleCancel 是触发 Server 生命周期收束的取消函数。
|
||||
// lifecycleCtx、lifecycleCancel 保存lifecycleCtx、lifecycle取消,供当前处理流程使用
|
||||
lifecycleCtx, lifecycleCancel := context.WithCancel(ctx)
|
||||
s.lifecycleCtx = lifecycleCtx
|
||||
s.lifecycleCancel = lifecycleCancel
|
||||
s.httpServer = httpServer
|
||||
s.httpDone = make(chan struct{})
|
||||
s.httpErr = nil
|
||||
@@ -498,10 +670,9 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.Unlock()
|
||||
|
||||
// 生命周期上下文取消时触发统一 Stop;该 goroutine 不登记到后台任务组,
|
||||
// 避免 Stop 等待自身造成死锁。
|
||||
// 进程生命周期 Context 取消时触发 HTTP Stop;应用组件关闭由 cmd 统一协调。
|
||||
go func() {
|
||||
<-lifecycleCtx.Done()
|
||||
<-ctx.Done()
|
||||
// stopCtx 是自动关闭 HTTP 服务时使用的有限时长上下文。
|
||||
// cancel 释放 stopCtx 的定时器资源。
|
||||
// stopCtx、cancel 保存stopCtx、cancel,供当前处理流程使用
|
||||
@@ -568,7 +739,7 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
if httpDone != nil && !waitForSignal(ctx, httpDone) {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) {
|
||||
if !s.waitForBackgroundContext(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
@@ -576,18 +747,11 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
s.stopped = true
|
||||
// httpServer 是需要执行优雅关闭的标准库 HTTP 服务。
|
||||
// httpDone 是监听 goroutine 退出的完成信号。
|
||||
// lifecycleCancel 是取消 Server 内部生命周期上下文的函数。
|
||||
// httpServer 保存httpServer,供当前处理流程使用
|
||||
httpServer := s.httpServer
|
||||
// httpDone 保存httpDone,供当前处理流程使用
|
||||
httpDone := s.httpDone
|
||||
// lifecycleCancel 保存lifecycle取消,供当前处理流程使用
|
||||
lifecycleCancel := s.lifecycleCancel
|
||||
s.lifecycleMu.Unlock()
|
||||
|
||||
if lifecycleCancel != nil {
|
||||
lifecycleCancel()
|
||||
}
|
||||
// shutdownErr 是 HTTP 优雅关闭返回的错误;后台等待错误由 worker 自身记录。
|
||||
var shutdownErr error
|
||||
if httpServer != nil {
|
||||
@@ -596,7 +760,7 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
if httpDone != nil && !waitForSignal(ctx, httpDone) {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) {
|
||||
if !s.waitForBackgroundContext(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
return shutdownErr
|
||||
@@ -611,13 +775,12 @@ func (s *Server) Run(ctx context.Context) error {
|
||||
return s.Wait()
|
||||
}
|
||||
|
||||
// WaitForBackground 等待恢复扫描器先退出,再等待其已经登记的批量 worker。
|
||||
// WaitForBackground 等待 Server 自有的 HTTP 后台任务退出;应用 worker 由生命周期协调器负责。
|
||||
func (s *Server) WaitForBackground() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
_ = s.waitForBackgroundContext(context.Background())
|
||||
s.waitForWorkers(10 * time.Second)
|
||||
}
|
||||
|
||||
// closedSignal 负责closedSignal相关处理。
|
||||
@@ -630,9 +793,10 @@ func closedSignal() chan struct{} {
|
||||
|
||||
// lifecycleContext 负责lifecycle上下文相关处理。
|
||||
func (s *Server) lifecycleContext() context.Context {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
return s.lifecycleCtx
|
||||
if s == nil || s.applicationLifecycle == nil {
|
||||
return context.Background()
|
||||
}
|
||||
return s.applicationLifecycle.Context()
|
||||
}
|
||||
|
||||
// startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。
|
||||
@@ -698,6 +862,17 @@ func (s *Server) finishBackgroundTask() {
|
||||
}
|
||||
}
|
||||
|
||||
// beginWorker 为仍需由 Server 等待的通用后台任务提供兼容测试入口;业务 worker 生命周期由应用协调器拥有。
|
||||
func (s *Server) beginWorker() func() {
|
||||
if s == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.beginBackgroundTask()
|
||||
return func() {
|
||||
s.finishBackgroundTask()
|
||||
}
|
||||
}
|
||||
|
||||
// waitForBackgroundContext 等待已登记后台任务退出;超时只结束当前等待,不创建游离等待 goroutine。
|
||||
func (s *Server) waitForBackgroundContext(ctx context.Context) bool {
|
||||
if s == nil {
|
||||
@@ -717,16 +892,6 @@ func (s *Server) waitForBackgroundContext(ctx context.Context) bool {
|
||||
return waitForSignal(ctx, done)
|
||||
}
|
||||
|
||||
// StartOrderReconciliationRecovery 启动受 Server 生命周期管理的订单补偿扫描器。
|
||||
func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) string {
|
||||
if s == nil || s.reconciliation == nil {
|
||||
return ""
|
||||
}
|
||||
return s.startBackgroundTaskContext("订单状态补偿扫描器", ctx, func() {
|
||||
s.reconciliation.Run(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
// taskRegistryForServer 返回 Server 的后台任务注册表;零值 Server 也会安全惰性初始化。
|
||||
func (s *Server) taskRegistryForServer() *taskRegistry {
|
||||
if s == nil {
|
||||
@@ -740,58 +905,6 @@ func (s *Server) taskRegistryForServer() *taskRegistry {
|
||||
return s.taskRegistry
|
||||
}
|
||||
|
||||
// beginWorker 负责begin工作器相关处理。
|
||||
func (s *Server) beginWorker() func() {
|
||||
s.workerMu.Lock()
|
||||
if s.workerCount == 0 {
|
||||
s.workersDone = make(chan struct{})
|
||||
}
|
||||
s.workerCount++
|
||||
s.workerMu.Unlock()
|
||||
return func() {
|
||||
s.workerMu.Lock()
|
||||
s.workerCount--
|
||||
if s.workerCount == 0 {
|
||||
close(s.workersDone)
|
||||
}
|
||||
s.workerMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// waitForWorkers 负责waitForWorkers相关处理。
|
||||
func (s *Server) waitForWorkers(timeout time.Duration) {
|
||||
if timeout <= 0 {
|
||||
_ = s.waitForWorkersContext(context.Background())
|
||||
return
|
||||
}
|
||||
// ctx、cancel 分别表示有限等待上下文和释放定时器的函数。
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
_ = s.waitForWorkersContext(ctx)
|
||||
}
|
||||
|
||||
// waitForWorkersContext 等待批量 worker,并将等待限制在调用方的关闭上下文内。
|
||||
func (s *Server) waitForWorkersContext(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.workerMu.Lock()
|
||||
// done 保存done,供当前处理流程使用
|
||||
done := s.workersDone
|
||||
s.workerMu.Unlock()
|
||||
if done == nil {
|
||||
// 零值 Server 尚未登记批量 worker,可直接视为已完成。
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
s.Logger.Warn("等待后台 worker 退出超时")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSignal 在关闭上下文取消或目标信号到达时返回,避免无界阻塞。
|
||||
func waitForSignal(ctx context.Context, signal <-chan struct{}) bool {
|
||||
select {
|
||||
|
||||
@@ -38,15 +38,49 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
|
||||
// mgr 是使用空处理器的测试账号管理器。
|
||||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||||
// srv 是未启用聊天服务的基础测试 HTTP 服务。
|
||||
// dependencies 保存测试 Server 使用的基础设施工厂,避免 Server 直接持有 Store。
|
||||
dependencies, dependencyErr := adapter.NewDependencies(store)
|
||||
if dependencyErr != nil {
|
||||
t.Fatalf("NewDependencies: %v", dependencyErr)
|
||||
// orderDependencies 保存订单应用服务专用的测试装配能力,确保 Server 不从通用容器回退读取订单依赖。
|
||||
orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store)
|
||||
if orderDependencyErr != nil {
|
||||
t.Fatalf("NewOrderDependencies: %v", orderDependencyErr)
|
||||
}
|
||||
// accountDependencies 保存测试 Server 的账号专用装配能力,避免回退到通用容器。
|
||||
accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store)
|
||||
if accountDependencyErr != nil {
|
||||
t.Fatalf("NewAccountDependencies: %v", accountDependencyErr)
|
||||
}
|
||||
// itemDependencies 保存测试 Server 的商品专用装配能力,避免回退到通用容器。
|
||||
itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store)
|
||||
if itemDependencyErr != nil {
|
||||
t.Fatalf("NewItemDependencies: %v", itemDependencyErr)
|
||||
}
|
||||
// chatDependencies 保存聊天测试使用的显式适配器工厂。
|
||||
chatDependencies := adapter.NewChatDependencies(store)
|
||||
// systemDependencies 保存健康检查与补偿扫描测试使用的显式适配器工厂。
|
||||
systemDependencies := adapter.NewSystemDependencies(store)
|
||||
// automationDependencies 保存自动化测试使用的显式适配器工厂及构造错误。
|
||||
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
|
||||
if automationDependencyErr != nil {
|
||||
t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr)
|
||||
}
|
||||
// miscDependencies 保存通知、分析和卡券测试使用的显式适配器工厂及构造错误。
|
||||
miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store)
|
||||
if miscDependencyErr != nil {
|
||||
t.Fatalf("NewMiscDependencies: %v", miscDependencyErr)
|
||||
}
|
||||
// adminSettingsDependencies 保存管理员和系统设置测试使用的显式适配器工厂。
|
||||
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
|
||||
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
|
||||
t.Fatal("显式 Server 依赖构造失败")
|
||||
}
|
||||
// platformDependencies 保存测试服务器显式注入的平台客户端集合。
|
||||
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
|
||||
if platformDependencyErr != nil {
|
||||
t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr)
|
||||
}
|
||||
// authentication 保存测试 HTTP 会话中间件需要的认证服务。
|
||||
authentication := &auth.Service{Store: store}
|
||||
// srv、err 保存测试 HTTP 服务构造结果及失败原因。
|
||||
srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil)
|
||||
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
@@ -77,6 +111,8 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
|
||||
chatService := chat.New(store)
|
||||
// srv.chat 在测试构造阶段一次性注入通信服务,模拟构造 option 的效果。
|
||||
srv.chat = chatService
|
||||
// applications.chat 重新绑定测试聊天服务,确保实时订阅适配器与 srv.chat 使用同一事件中心。
|
||||
srv.applications.chat = newChatSendingApplication(srv)
|
||||
return srv, store, cleanup
|
||||
}
|
||||
|
||||
@@ -95,15 +131,49 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
|
||||
// mgr 是未初始化测试使用的空处理器账号管理器。
|
||||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||||
// srv 是未初始化测试使用的 HTTP 服务实例。
|
||||
// dependencies 保存未初始化测试 Server 使用的基础设施工厂。
|
||||
dependencies, dependencyErr := adapter.NewDependencies(store)
|
||||
if dependencyErr != nil {
|
||||
t.Fatalf("NewDependencies: %v", dependencyErr)
|
||||
// orderDependencies 保存未初始化测试的订单专用装配能力。
|
||||
orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store)
|
||||
if orderDependencyErr != nil {
|
||||
t.Fatalf("NewOrderDependencies: %v", orderDependencyErr)
|
||||
}
|
||||
// accountDependencies 保存未初始化测试的账号专用装配能力。
|
||||
accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store)
|
||||
if accountDependencyErr != nil {
|
||||
t.Fatalf("NewAccountDependencies: %v", accountDependencyErr)
|
||||
}
|
||||
// itemDependencies 保存未初始化测试的商品专用装配能力。
|
||||
itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store)
|
||||
if itemDependencyErr != nil {
|
||||
t.Fatalf("NewItemDependencies: %v", itemDependencyErr)
|
||||
}
|
||||
// chatDependencies 保存未初始化测试使用的聊天适配器工厂。
|
||||
chatDependencies := adapter.NewChatDependencies(store)
|
||||
// systemDependencies 保存未初始化测试使用的系统适配器工厂。
|
||||
systemDependencies := adapter.NewSystemDependencies(store)
|
||||
// automationDependencies 保存未初始化测试使用的自动化适配器工厂及构造错误。
|
||||
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
|
||||
if automationDependencyErr != nil {
|
||||
t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr)
|
||||
}
|
||||
// miscDependencies 保存未初始化测试使用的杂项适配器工厂及构造错误。
|
||||
miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store)
|
||||
if miscDependencyErr != nil {
|
||||
t.Fatalf("NewMiscDependencies: %v", miscDependencyErr)
|
||||
}
|
||||
// adminSettingsDependencies 保存未初始化测试使用的管理员设置适配器工厂。
|
||||
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
|
||||
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
|
||||
t.Fatal("显式 Server 依赖构造失败")
|
||||
}
|
||||
// platformDependencies 保存未初始化测试服务器显式注入的平台客户端集合。
|
||||
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
|
||||
if platformDependencyErr != nil {
|
||||
t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr)
|
||||
}
|
||||
// authentication 保存未初始化数据库上的会话中间件依赖。
|
||||
authentication := &auth.Service{Store: store}
|
||||
// srv、err 保存未初始化测试服务构造结果及失败原因。
|
||||
srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil)
|
||||
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
writeJSON(w, http.StatusOK, newSettingsResponse(m))
|
||||
}
|
||||
|
||||
// allSettings 负责all设置相关处理。
|
||||
@@ -199,7 +199,7 @@ func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
writeJSON(w, http.StatusOK, newSettingsResponse(m))
|
||||
}
|
||||
|
||||
// setSetting 负责set设置相关处理。
|
||||
@@ -447,7 +447,7 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settingsResponse(settings))
|
||||
writeJSON(w, http.StatusOK, newSettingsResponse(settings))
|
||||
}
|
||||
|
||||
// getUserSetting 负责get用户设置相关处理。
|
||||
|
||||
@@ -395,7 +395,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
|
||||
if publicSettingsDecodeErr := json.Unmarshal(publicSettingsRecorder.Body.Bytes(), &publicSettingsValue); publicSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode public settings response: %v", publicSettingsDecodeErr)
|
||||
}
|
||||
if publicSettingsValue == nil {
|
||||
if publicSettingsValue.Entries == nil {
|
||||
t.Fatal("public settings response must be an object")
|
||||
}
|
||||
|
||||
@@ -414,7 +414,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
|
||||
if allSettingsDecodeErr := json.Unmarshal(allSettingsRecorder.Body.Bytes(), &allSettingsValue); allSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode all settings response: %v", allSettingsDecodeErr)
|
||||
}
|
||||
if allSettingsValue == nil {
|
||||
if allSettingsValue.Entries == nil {
|
||||
t.Fatal("all settings response must be an object")
|
||||
}
|
||||
|
||||
@@ -433,7 +433,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
|
||||
if userSettingsDecodeErr := json.Unmarshal(userSettingsRecorder.Body.Bytes(), &userSettingsValue); userSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode user settings response: %v", userSettingsDecodeErr)
|
||||
}
|
||||
if userSettingsValue == nil {
|
||||
if userSettingsValue.Entries == nil {
|
||||
t.Fatal("user settings response must be an object")
|
||||
}
|
||||
|
||||
@@ -462,12 +462,18 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
|
||||
if qrStatusDecodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &qrStatusValue); qrStatusDecodeErr != nil {
|
||||
t.Fatalf("decode qr status response: %v", qrStatusDecodeErr)
|
||||
}
|
||||
if qrStatusValue["status"] != "waiting" || qrStatusValue["custom_field"] != "kept" {
|
||||
if qrStatusValue.Status != "waiting" || qrStatusValue.SessionID != "contract-qr" {
|
||||
t.Fatalf("qr status response=%+v", qrStatusValue)
|
||||
}
|
||||
// leaked 表示二维码状态响应是否意外包含敏感 Cookie 字段。
|
||||
if _, leaked := qrStatusValue["cookies"]; leaked {
|
||||
t.Fatalf("qr status response leaked cookies: %+v", qrStatusValue)
|
||||
var rawQR map[string]any
|
||||
// decodeErr 表示原始二维码响应反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &rawQR); decodeErr != nil {
|
||||
t.Fatalf("decode raw qr status response: %v", decodeErr)
|
||||
}
|
||||
// leaked 表示原始响应是否包含不应暴露的 Cookie 字段。
|
||||
if _, leaked := rawQR["cookies"]; leaked {
|
||||
t.Fatalf("qr status response leaked cookies: %+v", rawQR)
|
||||
}
|
||||
|
||||
// srv.QRLogin 替换为完成验证场景的测试替身。
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
@@ -572,6 +574,54 @@ type orderDetailResponse struct {
|
||||
Data orderDTO `json:"data"`
|
||||
}
|
||||
|
||||
// orderUpdateRequestDTO 是订单更新接口的具名请求 DTO,保留旧客户端的状态字段别名。
|
||||
type orderUpdateRequestDTO struct {
|
||||
// OrderStatus 是订单状态补丁。
|
||||
OrderStatus *string `json:"order_status"`
|
||||
// Status 是旧客户端使用的订单状态别名。
|
||||
Status *string `json:"status"`
|
||||
// ItemID 是商品标识补丁。
|
||||
ItemID *string `json:"item_id"`
|
||||
// BuyerID 是买家标识补丁。
|
||||
BuyerID *string `json:"buyer_id"`
|
||||
// SpecName 是规格名称补丁。
|
||||
SpecName *string `json:"spec_name"`
|
||||
// SpecValue 是规格值补丁。
|
||||
SpecValue *string `json:"spec_value"`
|
||||
// Quantity 是兼容字符串或数字格式的购买数量。
|
||||
Quantity *any `json:"quantity"`
|
||||
// Amount 是兼容字符串或数字格式的订单金额。
|
||||
Amount *any `json:"amount"`
|
||||
// ReceiverName 是收货人补丁。
|
||||
ReceiverName *string `json:"receiver_name"`
|
||||
// ReceiverPhone 是收货电话补丁。
|
||||
ReceiverPhone *string `json:"receiver_phone"`
|
||||
// ReceiverAddress 是收货地址补丁。
|
||||
ReceiverAddress *string `json:"receiver_address"`
|
||||
// ReceiverCity 是收货城市补丁。
|
||||
ReceiverCity *string `json:"receiver_city"`
|
||||
// ChatID 是聊天会话补丁。
|
||||
ChatID *string `json:"chat_id"`
|
||||
// SystemShipped 表示是否由系统完成发货。
|
||||
SystemShipped *bool `json:"system_shipped"`
|
||||
// ItemTitle 是关联商品标题补丁。
|
||||
ItemTitle *string `json:"item_title"`
|
||||
}
|
||||
|
||||
// manualShipRequestDTO 是批量手动发货接口的具名请求 DTO。
|
||||
type manualShipRequestDTO struct {
|
||||
// OrderIDs 是待处理订单标识列表。
|
||||
OrderIDs []string `json:"order_ids"`
|
||||
// ShipMode 是发货模式。
|
||||
ShipMode string `json:"ship_mode"`
|
||||
}
|
||||
|
||||
// qrVerificationRequestDTO 是扫码风控验证完成接口的具名请求 DTO。
|
||||
type qrVerificationRequestDTO struct {
|
||||
// TargetAccountID 是可选的待重新授权本地账号标识。
|
||||
TargetAccountID string `json:"target_account_id"`
|
||||
}
|
||||
|
||||
// orderRefreshDetailResponse 是订单刷新后返回的远端详情 DTO。
|
||||
type orderRefreshDetailResponse struct {
|
||||
// Quantity 是订单购买数量。
|
||||
@@ -595,7 +645,33 @@ type orderRefreshResponse struct {
|
||||
// Summary 是刷新统计摘要。
|
||||
Summary orderRefreshSummary `json:"summary"`
|
||||
// Results 是逐账号或逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
Results []orderRefreshResultDTO `json:"results"`
|
||||
}
|
||||
|
||||
// orderRefreshResultDTO 是订单刷新批次中单条结果的稳定响应 DTO;可选字段只在对应阶段产生时返回。
|
||||
type orderRefreshResultDTO struct {
|
||||
// Success 表示当前账号或订单刷新是否成功。
|
||||
Success bool `json:"success"`
|
||||
// CookieID 是当前结果关联的账号标识。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// Discovered 是当前账号发现的新订单数量。
|
||||
Discovered *int `json:"discovered,omitempty"`
|
||||
// Updated 是当前账号更新的订单数量。
|
||||
Updated *int `json:"updated,omitempty"`
|
||||
// SoftDeleted 表示当前账号是否标记了失效订单。
|
||||
SoftDeleted *bool `json:"soft_deleted,omitempty"`
|
||||
// OrderID 是单订单刷新结果关联的平台订单标识。
|
||||
OrderID string `json:"order_id,omitempty"`
|
||||
// Stage 是刷新失败或完成所处的业务阶段。
|
||||
Stage string `json:"stage,omitempty"`
|
||||
// Message 是面向客户端的结果说明。
|
||||
Message string `json:"message,omitempty"`
|
||||
// Error 是当前结果的兼容错误文本。
|
||||
Error string `json:"error,omitempty"`
|
||||
// OldStatus 是刷新前的订单状态。
|
||||
OldStatus string `json:"old_status,omitempty"`
|
||||
// NewStatus 是刷新后的订单状态。
|
||||
NewStatus string `json:"new_status,omitempty"`
|
||||
}
|
||||
|
||||
// orderRefreshSummary 是订单列表刷新统计摘要 DTO。
|
||||
@@ -639,7 +715,23 @@ type manualShipResponse struct {
|
||||
// FailedCount 是失败发货数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// Results 是逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
Results []orderMutationResultDTO `json:"results"`
|
||||
}
|
||||
|
||||
// orderMutationResultDTO 是手动发货逐订单结果的稳定响应 DTO。
|
||||
type orderMutationResultDTO struct {
|
||||
// OrderID 是当前结果关联的平台订单标识。
|
||||
OrderID string `json:"order_id"`
|
||||
// Status 是发货后订单状态或失败阶段。
|
||||
Status string `json:"status"`
|
||||
// Success 表示当前订单是否发货成功。
|
||||
Success bool `json:"success"`
|
||||
// Message 是当前订单的处理说明。
|
||||
Message string `json:"message"`
|
||||
// ReconciliationID 是可选的补偿记录标识。
|
||||
ReconciliationID string `json:"reconciliation_id,omitempty"`
|
||||
// ReconciliationWarning 是可选的补偿告警文本。
|
||||
ReconciliationWarning string `json:"reconciliation_warning,omitempty"`
|
||||
}
|
||||
|
||||
// importOrdersResponse 是订单导入接口的具名响应 DTO。
|
||||
@@ -655,7 +747,17 @@ type importOrdersResponse struct {
|
||||
// FailedCount 是失败导入数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// Results 是逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
Results []orderImportResultDTO `json:"results"`
|
||||
}
|
||||
|
||||
// orderImportResultDTO 是订单导入逐订单结果的稳定响应 DTO。
|
||||
type orderImportResultDTO struct {
|
||||
// OrderID 是当前结果关联的平台订单标识。
|
||||
OrderID string `json:"order_id"`
|
||||
// Success 表示当前订单是否导入成功。
|
||||
Success bool `json:"success"`
|
||||
// Message 是当前订单的处理说明。
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// aiReplySettingsResponse 是账号 AI 回复设置接口的具名响应 DTO。
|
||||
@@ -1364,11 +1466,69 @@ type qrLoginGenerateResponse struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// settingsResponse 是动态设置查询的具名边界类型,键和值仍由设置仓库定义。
|
||||
type settingsResponse map[string]string
|
||||
// settingsEntryDTO 是单条设置键值的具名 DTO;仅在 HTTP 边界内部用于稳定排序和校验。
|
||||
type settingsEntryDTO struct {
|
||||
// Key 是设置项的稳定键名。
|
||||
Key string `json:"key"`
|
||||
// Value 是设置项的脱敏文本值。
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// qrLoginStatusResponse 是二维码状态的兼容响应类型,允许上游扩展非敏感字段。
|
||||
type qrLoginStatusResponse map[string]any
|
||||
// settingsResponse 是设置查询的具名响应 DTO;序列化时保持旧客户端的顶层键值对象形状。
|
||||
type settingsResponse struct {
|
||||
// Entries 保存设置键值,避免 DTO 直接暴露动态 map 字段。
|
||||
Entries []settingsEntryDTO `json:"-"`
|
||||
}
|
||||
|
||||
// newSettingsResponse 将应用层动态设置键值转换为具名 HTTP 响应 DTO。
|
||||
func newSettingsResponse(values map[string]string) settingsResponse {
|
||||
// entries 保存待编码的设置项;顺序不影响兼容 JSON 对象,但便于测试和日志稳定。
|
||||
entries := make([]settingsEntryDTO, 0, len(values))
|
||||
// key 是当前设置名称;value 是对应的非敏感配置值。
|
||||
for key, value := range values {
|
||||
entries = append(entries, settingsEntryDTO{Key: key, Value: value})
|
||||
}
|
||||
return settingsResponse{Entries: entries}
|
||||
}
|
||||
|
||||
// MarshalJSON 保持设置接口原有的顶层键值对象契约,同时隐藏内部动态字段实现。
|
||||
func (response settingsResponse) MarshalJSON() ([]byte, error) {
|
||||
// values 保存兼容旧客户端的顶层设置对象。
|
||||
values := make(map[string]string, len(response.Entries))
|
||||
// entry 是当前待恢复为顶层设置字段的具名条目。
|
||||
for _, entry := range response.Entries {
|
||||
values[entry.Key] = entry.Value
|
||||
}
|
||||
return json.Marshal(values)
|
||||
}
|
||||
|
||||
// UnmarshalJSON 将旧客户端顶层设置对象解析为具名条目,供契约测试和边界适配使用。
|
||||
func (response *settingsResponse) UnmarshalJSON(data []byte) error {
|
||||
// values 保存收到的顶层设置对象;设置值均按字符串处理以避免秘密类型扩散。
|
||||
var values map[string]string
|
||||
// err 表示旧版顶层设置对象反序列化失败的原因。
|
||||
if err := json.Unmarshal(data, &values); err != nil {
|
||||
return err
|
||||
}
|
||||
*response = newSettingsResponse(values)
|
||||
return nil
|
||||
}
|
||||
|
||||
// qrLoginStatusResponse 是二维码状态的稳定响应 DTO,仅暴露非敏感状态和持久化结果。
|
||||
type qrLoginStatusResponse struct {
|
||||
// Success 表示当前扫码状态请求是否正常完成。
|
||||
Success bool `json:"success,omitempty"`
|
||||
// Status 是扫码会话当前状态。
|
||||
Status string `json:"status"`
|
||||
// Message 是可选的平台提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
// SessionID 是可选的扫码会话标识。
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
// AccountID 是扫码成功后创建或更新的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示扫码成功后是否新建本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
|
||||
// qrLoginVerificationResponse 是二维码风控验证完成的具名响应 DTO。
|
||||
type qrLoginVerificationResponse struct {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// withTransaction 在 Server 应用层统一创建、提交或回滚数据库事务。
|
||||
// 调用方只描述事务内的数据库操作,不再直接管理事务生命周期。
|
||||
// withTransaction 负责withTransaction相关处理。
|
||||
func (s *Server) withTransaction(ctx context.Context, work func(*sql.Tx) error) error {
|
||||
// repository 是当前 Server 装配的事务执行边界。
|
||||
repository := s.transactionRepository
|
||||
if repository == nil {
|
||||
return errors.New("事务 repository 未初始化")
|
||||
}
|
||||
return repository.WithTransaction(ctx, work)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestWithTransactionCommitAndRollback 验证统一事务入口能够提交成功操作并回滚失败操作。
|
||||
func TestWithTransactionCommitAndRollback(t *testing.T) {
|
||||
// srv 是使用测试数据库的 Server。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// ctx 是本测试使用的可取消上下文。
|
||||
ctx := context.Background()
|
||||
// createErr 是创建测试表失败时的错误。
|
||||
if _, createErr := store.DB.ExecContext(ctx, `CREATE TABLE unit_of_work_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil {
|
||||
t.Fatalf("创建事务测试表失败: %v", createErr)
|
||||
}
|
||||
// commitErr 是提交事务执行结果。
|
||||
commitErr := srv.withTransaction(ctx, func(tx *sql.Tx) error {
|
||||
// err 保存err,供当前处理流程使用
|
||||
_, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (1, 'committed')`)
|
||||
return err
|
||||
})
|
||||
if commitErr != nil {
|
||||
t.Fatalf("事务提交失败: %v", commitErr)
|
||||
}
|
||||
// rollbackErr 是故意触发回滚事务的错误。
|
||||
rollbackErr := errors.New("故意回滚")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := srv.withTransaction(ctx, func(tx *sql.Tx) error {
|
||||
// err 保存err,供当前处理流程使用
|
||||
_, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (2, 'rolled back')`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rollbackErr
|
||||
}); !errors.Is(err, rollbackErr) {
|
||||
t.Fatalf("事务回滚错误不匹配: %v", err)
|
||||
}
|
||||
// count 是事务提交后测试表中的记录数。
|
||||
var count int
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil {
|
||||
t.Fatalf("查询事务测试结果失败: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("事务回滚后记录数应为 1,got %d", count)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user