重构:统一应用服务与基础设施适配边界

将账号、认证、管理员、分析、自动化、卡券、聊天、商品、关键词、设置和订单能力迁移到 application 与 adapter,删除 Server 内对应的旧仓储和业务服务实现,并收紧架构检查。

完善批量发布与订单刷新生命周期、凭证写回、账号任务补偿、订单 reconciliation、通知和敏感数据边界;补充正常、失败、取消、并发、越权及多方言回归测试,并修正 MySQL 延迟任务表的 InnoDB 配置。

修复空卡密响应为 null 时前端加载失败的问题,重建嵌入式前端资产;重写重构总计划,清除历史流水并明确阶段 1 至 10 各对应一次完整迭代和一个 PR。

验证:make check;make test-server-race;npm test/typecheck/comments:check/build;Docker SQLite/MySQL 8.4/PostgreSQL 17 TestMultiDB_*。
This commit is contained in:
Christ committed 2026-08-16 23:51:06 +08:00
1 parent 19a7d5f924
commit 375e84d663
239 files changed
+23870 -7871

No files matched your search

-270
View File
@@ -1,270 +0,0 @@
package server
import (
"context"
"errors"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
)
// accountLoginRepository 定义账号登录服务写入凭证、审计登录、更新资料和读取账号状态所需的最小能力。
type accountLoginRepository interface {
// LockCredentials 串行化账号登录凭证变更。
LockCredentials(accountID string) func()
// CreateCookieOwned 创建用户拥有的账号凭证。
CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error
// LoadPlatformDetail 读取平台登录所需的最小账号视图。
LoadPlatformDetail(ctx context.Context, accountID string) (*db.CookieDetail, error)
// UpdateFlatCookieOwned 更新用户拥有账号的扁平 Cookie。
UpdateFlatCookieOwned(ctx context.Context, detail *db.CookieDetail, cookies string) error
// UpdateRenewalCookie 更新账号 Cookie 和 metadata。
UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error
// ClearTokens 清理账号旧连接 Token。
ClearTokens(ctx context.Context, accountID string) error
// GetStatus 返回账号是否启用。
GetStatus(ctx context.Context, accountID string) bool
// MarkLogin 保存账号最近一次成功登录方式。
MarkLogin(ctx context.Context, accountID, method string, at int64) error
// SetStatusWithReason 更新账号启用状态及禁用原因。
SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error
// AddLoginLog 写入账号登录审计记录。
AddLoginLog(ctx context.Context, log db.AccountLoginLog) error
// UpdateProfile 保存账号展示资料。
UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error
}
// storeAccountLoginRepository 将完整 Store 适配为账号登录服务窄 repository。
type storeAccountLoginRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// storeAccountProfileRepository 将 Server 的摘要查询适配为账号应用层 Port。
type storeAccountProfileRepository struct {
// store 提供账号摘要查询能力;凭证字段不会通过该适配器读取。
store *db.Store
}
// GetOwnedSummary 查询指定用户拥有的非敏感账号摘要。
func (r storeAccountProfileRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.Summary, error) {
// summary 保存数据库返回的非敏感账号摘要。
summary, err := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID)
if err != nil {
if errors.Is(err, db.ErrForbidden) {
return accountapp.Summary{}, accountapp.ErrForbidden
}
if errors.Is(err, db.ErrNotFound) {
// ownerID 和 ownerErr 用于区分不存在账号与跨用户账号,保持 HTTP 兼容状态码。
ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, accountID)
if ownerErr == nil && ownerID != userID {
return accountapp.Summary{}, accountapp.ErrForbidden
}
return accountapp.Summary{}, accountapp.ErrNotFound
}
return accountapp.Summary{}, err
}
return accountapp.Summary{
ID: summary.ID, UserID: summary.UserID, Remark: summary.Remark,
Nickname: summary.Nickname, AvatarURL: summary.AvatarURL,
}, nil
}
// DeleteOwned 在凭证锁内再次确认账号归属并删除账号,避免停止 fencing 期间误删被替换账号。
func (r storeAccountProfileRepository) DeleteOwned(ctx context.Context, userID int64, accountID string) error {
if r.store == nil || r.store.Cookies == nil {
return errors.New("账号删除存储未初始化")
}
// unlock 保护最终归属复核与删除之间的账号凭证状态,避免并发替换穿透删除边界。
unlock := r.store.LockAccountCredentials(accountID)
defer unlock()
// summary、summaryErr 保存锁内的非敏感归属复核结果。
if _, summaryErr := r.GetOwnedSummary(ctx, userID, accountID); summaryErr != nil {
return summaryErr
}
return r.store.Cookies.Delete(ctx, accountID)
}
// LockCredentials 委托账号凭证锁。
func (r storeAccountLoginRepository) LockCredentials(accountID string) func() {
return r.store.LockAccountCredentials(accountID)
}
// CreateCookieOwned 委托账号凭证创建。
func (r storeAccountLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error {
return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
}
// LoadPlatformDetail 委托平台账号视图查询并转换为 Server 内部模型。
func (r storeAccountLoginRepository) LoadPlatformDetail(ctx context.Context, accountID string) (*db.CookieDetail, error) {
// data 和 err 保存平台运行视图查询结果。
data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if err != nil {
return nil, err
}
// summary 只补充非敏感版本字段,避免为乐观冲突检查读取或解密登录密码。
summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID)
if summaryErr != nil {
return nil, summaryErr
}
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt}, nil
}
// UpdateFlatCookieOwned 委托扁平 Cookie 更新并清除旧的完整 Cookie Jar 快照。
func (r storeAccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context, detail *db.CookieDetail, cookies string) error {
if detail == nil {
return db.ErrNotFound
}
// metadata 保存移除完整 Cookie Jar 快照后的元数据。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix())
}
// FindAccount 只读取扫码登录所需的账号归属,不解密 Cookie、密码或 metadata。
func (r storeAccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
// ownerID 保存数据库返回的账号所属用户标识。
ownerID, err := r.store.Cookies.GetOwnerID(ctx, accountID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return accountapp.QRLoginAccount{}, accountapp.ErrNotFound
}
return accountapp.QRLoginAccount{}, err
}
return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil
}
// UpdateQRCookieFlatOwned 更新扫码登录账号的扁平 Cookie,并清除旧的完整快照。
func (r storeAccountLoginRepository) UpdateQRCookieFlatOwned(ctx context.Context, accountID, cookies string) error {
// detail 保存平台运行视图;该窄视图只在凭证适配器内部读取 metadata。
detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if err != nil {
return err
}
// metadata 保存移除旧快照后的加密 metadata 文本。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
}
// UpdateQRCookieSnapshotOwned 更新扫码 Cookie,并把完整快照合并进加密 metadata。
func (r storeAccountLoginRepository) UpdateQRCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
// detail 保存平台运行视图;完整 metadata 不向应用服务层泄露。
detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if err != nil {
return err
}
// browserSnapshot 保存转换后的浏览器 Cookie 快照,仅在数据库适配器内使用。
browserSnapshot := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
// snapshotEntry 表示当前待转换的应用层 Cookie 快照。
for _, snapshotEntry := range snapshot {
browserSnapshot = append(browserSnapshot, cookierefresh.BrowserCookie{
Name: snapshotEntry.Name, Value: snapshotEntry.Value, Domain: snapshotEntry.Domain,
Path: snapshotEntry.Path, Expires: snapshotEntry.Expires, HTTPOnly: snapshotEntry.HTTPOnly,
Secure: snapshotEntry.Secure, SameSite: snapshotEntry.SameSite, PartitionKey: snapshotEntry.PartitionKey,
})
}
// metadata 保存快照合并后的加密 metadata 文本。
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot)
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
}
// UpdateRenewalCookie 委托 Cookie 与 metadata 更新。
func (r storeAccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error {
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at)
}
// ClearTokens 委托账号 Token 清理;未启用 Token repository 时保持兼容空操作。
func (r storeAccountLoginRepository) ClearTokens(ctx context.Context, accountID string) error {
if r.store.Tokens == nil {
return nil
}
return r.store.Tokens.Clear(ctx, accountID)
}
// GetStatus 委托账号启用状态查询。
func (r storeAccountLoginRepository) GetStatus(ctx context.Context, accountID string) bool {
return r.store.Cookies.GetStatus(ctx, accountID)
}
// MarkLogin 委托账号最近一次成功登录方式保存。
func (r storeAccountLoginRepository) MarkLogin(ctx context.Context, accountID, method string, at int64) error {
return r.store.Cookies.MarkLogin(ctx, accountID, method, at)
}
// SetStatusWithReason 委托账号启用状态更新。
func (r storeAccountLoginRepository) SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error {
return r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason)
}
// AddLoginLog 委托账号登录审计记录写入;未启用审计 repository 时保持兼容空操作。
func (r storeAccountLoginRepository) AddLoginLog(ctx context.Context, log db.AccountLoginLog) error {
if r.store.LoginLogs == nil {
return nil
}
return r.store.LoginLogs.Add(ctx, log)
}
// UpdateProfile 委托账号展示资料更新。
func (r storeAccountLoginRepository) UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error {
return r.store.Cookies.UpdateProfile(ctx, accountID, nickname, avatarURL)
}
// newStoreAccountLoginRepository 从完整 Store 构造账号登录服务窄 repository。
func newStoreAccountLoginRepository(store *db.Store) accountLoginRepository {
if store == nil || store.Cookies == nil {
return nil
}
return storeAccountLoginRepository{store: store}
}
// newStoreQRLoginRepository 从完整 Store 构造扫码登录应用服务所需的窄凭证端口。
func newStoreQRLoginRepository(store *db.Store) accountapp.QRLoginRepository {
if store == nil || store.Cookies == nil {
return nil
}
return storeQRLoginRepository{store: store}
}
// storeQRLoginRepository 将 Store 的扫码凭证能力限制在应用服务定义的窄端口内。
type storeQRLoginRepository struct {
// store 提供数据库凭证读写能力,仅在本适配器内部访问。
store *db.Store
}
// LockCredentials 串行化扫码登录对同一账号的凭证变更。
func (r storeQRLoginRepository) LockCredentials(accountID string) func() {
return r.store.LockAccountCredentials(accountID)
}
// FindAccount 只返回账号存在性和归属,不读取 Cookie、密码或 metadata。
func (r storeQRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
return storeAccountLoginRepository(r).FindAccount(ctx, accountID)
}
// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。
func (r storeQRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error {
return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
}
// UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并清除完整快照。
func (r storeQRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error {
return storeAccountLoginRepository(r).UpdateQRCookieFlatOwned(ctx, accountID, cookies)
}
// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。
func (r storeQRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
return storeAccountLoginRepository(r).UpdateQRCookieSnapshotOwned(ctx, accountID, cookies, snapshot)
}
// ClearTokens 清理扫码登录前遗留的旧连接 Token。
func (r storeQRLoginRepository) ClearTokens(ctx context.Context, accountID string) error {
// clearErr 保存旧连接 Token 清理结果;凭证已成功写入时该错误不阻断扫码登录。
return storeAccountLoginRepository(r).ClearTokens(ctx, accountID)
}
// 确保 Store 适配器始终覆盖账号登录服务所需的全部能力。
var _ accountLoginRepository = storeAccountLoginRepository{}
// 确保扫码凭证适配器始终覆盖应用服务定义的最小端口。
var _ accountapp.QRLoginRepository = storeQRLoginRepository{}
@@ -0,0 +1,22 @@
package server
import (
"context"
"testing"
)
// TestServerCookieWriterRejectsMissingRepository 验证 Server 凭证写入适配器缺少 Port 时快速失败。
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 不应伪装成功")
}
}
+19 -56
View File
@@ -8,9 +8,8 @@ import (
"sync"
"time"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/protocol"
)
// accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。
@@ -18,7 +17,9 @@ type accountLoginService struct {
// server 提供账号存储、运行时管理器和扫码会话持久化依赖。
server *Server
// repository 提供账号登录服务所需的最小凭证持久化能力。
repository accountLoginRepository
repository accountapp.CredentialRepository
// summaryRepository 提供不解密凭证的账号摘要和归属查询能力。
summaryRepository accountapp.AccountSummaryRepository
// createApplication 提供已迁移的手动 Cookie 登录应用用例。
createApplication *accountapp.LoginService
// qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。
@@ -45,7 +46,7 @@ func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, user
// serverCookieWriter 将本次请求中的明文 Cookie 限制在 Server 基础设施适配器内。
type serverCookieWriter struct {
// repository 提供凭证锁、写入和旧 Token 清理能力。
repository accountLoginRepository
repository accountapp.CredentialRepository
// cookies 保存当前请求明文 Cookie;仅在 CreateOwnedCookie 调用期间使用,不进入应用层模型。
cookies string
// logger 提供旧 Token 清理失败的脱敏日志能力。
@@ -87,7 +88,7 @@ func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID str
return loadErr
}
if detail == nil || detail.UserID != userID {
return db.ErrForbidden
return accountapp.ErrForbidden
}
if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision {
return accountapp.ErrCredentialConflict
@@ -108,49 +109,13 @@ func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService,
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
}
// newAccountQRLoginApplication 构造扫码登录应用服务及其凭证、生命周期适配器。
func newAccountQRLoginApplication(server *Server) (*accountapp.QRLoginService, error) {
return accountapp.NewQRLoginService(newStoreQRLoginRepository(server.Store), serverQRLoginLifecycle{server: server})
}
// serverAccountProfilePort 将平台资料刷新适配为账号应用层 Port。
type serverAccountProfilePort struct {
// server 提供平台会话、凭证锁、资料保存和运行时同步能力。
server *Server
}
// RefreshProfile 执行平台资料刷新,并把平台结果转换为应用层 DTO。
func (p serverAccountProfilePort) RefreshProfile(ctx context.Context, input accountapp.ProfileInput) (accountapp.ProfileResult, error) {
// detail 是兼容 Server 资料刷新器所需的非敏感账号摘要模型。
detail := &db.CookieDetail{
ID: input.Summary.ID, UserID: input.Summary.UserID,
Remark: input.Summary.Remark, Nickname: input.Summary.Nickname,
AvatarURL: input.Summary.AvatarURL,
}
// nickname、avatarURL 和 profileErr 保存平台资料刷新后的展示结果。
nickname, avatarURL, profileErr := p.server.refreshAccountProfile(ctx, detail)
return accountapp.ProfileResult{
AccountID: input.AccountID, Nickname: nickname,
AvatarURL: avatarURL, ErrorMessage: profileErr,
}, nil
}
// newAccountProfileApplication 从 Server 的数据库和平台能力构造账号资料应用服务。
func newAccountProfileApplication(server *Server) (*accountapp.ProfileService, error) {
// repository 是只返回非敏感摘要的数据库适配器。
repository := storeAccountProfileRepository{store: server.Store}
// profilePort 是负责平台请求和资料持久化的 Server 适配器。
profilePort := serverAccountProfilePort{server: server}
return accountapp.NewProfileService(repository, profilePort)
}
// accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。
func (s *Server) accountLoginApplication() *accountLoginService {
return s.applicationServiceSet().accountLogin
}
// accountLoginRepositoryForServer 返回当前 Server 装配的账号登录持久化边界。
func (s *Server) accountLoginRepositoryForServer() accountLoginRepository {
func (s *Server) accountLoginRepositoryForServer() accountapp.CredentialRepository {
return s.accountLoginApplication().repository
}
@@ -253,21 +218,13 @@ func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userI
// cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。
cookies := qrString(result, "cookies")
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。
cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result)
// scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
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 = make([]accountapp.CookieSnapshot, 0, len(cookieSnapshot))
// cookie 保存当前浏览器 Cookie 快照,转换后不再依赖平台 DTO。
for _, cookie := range cookieSnapshot {
input.Snapshot = append(input.Snapshot, accountapp.CookieSnapshot{
Name: cookie.Name, Value: cookie.Value, Domain: cookie.Domain, Path: cookie.Path,
Expires: cookie.Expires, HTTPOnly: cookie.HTTPOnly, Secure: cookie.Secure,
SameSite: cookie.SameSite, PartitionKey: cookie.PartitionKey,
})
}
input.Snapshot = cookieSnapshot
}
// resultValue 保存应用服务返回的非敏感持久化结果。
resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input)
@@ -281,7 +238,7 @@ func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userI
if errors.Is(persistErr, accountapp.ErrForbidden) {
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
}
if errors.Is(persistErr, db.ErrAlreadyExists) {
if errors.Is(persistErr, accountapp.ErrAlreadyExists) {
return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
}
return qrLoginPersistence{}, persistErr
@@ -300,9 +257,15 @@ func (svc *accountLoginService) refreshAndRestartAccount(ctx context.Context, us
// s 是当前账号登录应用服务依赖的 Server。
s := svc.server
// detail 和 err 保存资料摘要查询结果。
detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID)
_, err := svc.summaryRepository.GetOwnedSummary(ctx, userID, accountID)
if err == nil {
s.refreshAccountProfile(ctx, detail)
// 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 表示账号运行时重启错误。
@@ -0,0 +1,87 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// TestRequireCookieOwnershipPreservesHTTPCompatibility 验证账号所有权辅助函数保留未登录、越权、缺失和成功状态码。
func TestRequireCookieOwnershipPreservesHTTPCompatibility(t *testing.T) {
// srv、store、cleanup 保存当前测试使用的 HTTP 服务和数据库。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 是本测试共用的数据库上下文。
ctx := context.Background()
// _, createErr 保存第二个用户创建错误;用户主键随后从查询得到。
_, createErr := store.Users.Create(ctx, "summary-other", "[email protected]", "pw")
if createErr != nil {
t.Fatalf("创建第二用户失败: %v", createErr)
}
// other、otherLookupErr 保存第二个用户及读取错误。
other, otherLookupErr := store.Users.GetByUsername(ctx, "summary-other")
if otherLookupErr != nil {
t.Fatalf("读取第二用户失败: %v", otherLookupErr)
}
// saveErr 保存第二个用户账号的创建错误。
if saveErr := store.Cookies.Save(ctx, "other-account", "unb=other", other.ID); saveErr != nil {
t.Fatalf("创建第二用户账号失败: %v", saveErr)
}
// cases 覆盖所有权辅助函数的 HTTP 兼容分支。
cases := []struct {
// name 是当前 HTTP 所有权场景名称。
name string
// session 是请求上下文中的认证会话;nil 表示未登录。
session *db.Session
// accountID 是待校验账号标识。
accountID string
// wantStatus 是预期错误响应状态;成功场景为 0。
wantStatus int
// wantOwned 表示预期的所有权结论。
wantOwned bool
}{
{name: "unauthenticated", accountID: "acc1", wantStatus: http.StatusUnauthorized},
{name: "owned", session: &db.Session{UserID: 1}, accountID: "acc1", wantOwned: true},
{name: "forbidden", session: &db.Session{UserID: 1}, accountID: "other-account", wantStatus: http.StatusForbidden},
{name: "missing", session: &db.Session{UserID: 1}, accountID: "missing-account", wantStatus: http.StatusNotFound},
}
// testCase 表示当前正在验证的 HTTP 所有权场景。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// request 是注入测试会话后的所有权请求。
request := httptest.NewRequest(http.MethodGet, "/items", nil)
if testCase.session != nil {
request = request.WithContext(auth.WithSession(request.Context(), testCase.session))
}
// recorder 捕获所有权辅助函数的 HTTP 错误响应。
recorder := httptest.NewRecorder()
// owned 保存应用 Port 返回的所有权结论。
owned := srv.requireCookieOwnership(recorder, request, testCase.accountID)
if owned != testCase.wantOwned {
t.Fatalf("owned=%v,期望=%v", owned, testCase.wantOwned)
}
if testCase.wantStatus != 0 && recorder.Code != testCase.wantStatus {
t.Fatalf("status=%d,期望=%d body=%s", recorder.Code, testCase.wantStatus, recorder.Body.String())
}
})
}
}
// TestLoadCookieSummaryDetailUsesNonSensitiveApplicationModel 验证 Server 摘要兼容模型不携带 Cookie 或密码。
func TestLoadCookieSummaryDetailUsesNonSensitiveApplicationModel(t *testing.T) {
// srv、cleanup 保存当前测试使用的 HTTP 服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// detail、loadErr 保存应用 Port 返回的非敏感摘要及读取错误。
detail, loadErr := srv.loadCookieSummaryDetail(context.Background(), 1, "acc1")
if loadErr != nil {
t.Fatalf("读取账号摘要失败: %v", loadErr)
}
if detail.ID != "acc1" || detail.UserID != 1 {
t.Fatalf("摘要模型不完整: %+v", detail)
}
}
@@ -0,0 +1,36 @@
package server
import automationapp "xianyu-go/internal/application/automation"
// newApplicationAccountTaskSettingsResponse 将应用层账号任务设置转换为 HTTP DTO。
func newApplicationAccountTaskSettingsResponse(settings automationapp.AccountTaskSettings) accountTaskSettingsResponse {
return accountTaskSettingsResponse{
AccountID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent,
AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime,
LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt,
}
}
// newApplicationAccountTaskRunResponses 批量转换应用层账号任务运行记录。
func newApplicationAccountTaskRunResponses(runs []automationapp.AccountTaskRun) []accountTaskRunResponse {
// result 保存待写入响应的账号任务运行 DTO。
result := make([]accountTaskRunResponse, 0, len(runs))
// run 是当前待转换的应用层运行记录。
for _, run := range runs {
result = append(result, accountTaskRunResponse{
ID: run.ID, RunKey: run.RunKey, AccountID: run.CookieID, TaskType: run.TaskType,
TargetID: run.TargetID, RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount,
FailedCount: run.FailedCount, ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt,
StartedAt: run.StartedAt, FinishedAt: run.FinishedAt,
})
}
return result
}
// newApplicationAccountTaskSummaryResponse 将应用层账号任务摘要转换为 HTTP DTO。
func newApplicationAccountTaskSummaryResponse(summary automationapp.TaskSummary) accountTaskSummaryResponse {
return accountTaskSummaryResponse{
TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success,
Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message,
}
}
+21 -20
View File
@@ -3,18 +3,13 @@ package server
import (
"errors"
"net/http"
"regexp"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
automationapp "xianyu-go/internal/application/automation"
)
// accountTaskTimePattern 保存账号任务时间Pattern,供当前处理流程使用
var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`)
// mountAccountTasks 负责mount账号任务列表相关处理。
func (s *Server) mountAccountTasks(r chi.Router) {
r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings)
@@ -32,12 +27,12 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request)
return
}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := s.communicationApplication().GetAccountTaskSettings(r.Context(), cid)
settings, err := s.accountTaskApplication().GetSettings(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
return
}
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(settings))
writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(settings))
}
// updateAccountTaskSettings 负责update账号任务设置相关处理。
@@ -49,13 +44,15 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques
return
}
// input 保存input,供当前处理流程使用
var input db.AccountTaskSettings
var input automationapp.AccountTaskSettings
if decodeJSON(r, &input) != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// stored、err 保存stored、err,供当前处理流程使用
stored, err := s.communicationApplication().UpdateAccountTaskSettings(r.Context(), accountTaskUpdateInput{CookieID: cid, Settings: input})
input.CookieID = cid
// stored、err 保存应用服务规范化后的设置及写入错误。
stored, err := s.accountTaskApplication().UpdateSettings(r.Context(), input)
if err != nil {
if strings.Contains(err.Error(), "不能为空") || strings.Contains(err.Error(), "不能超过") || strings.Contains(err.Error(), "格式必须") {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -64,7 +61,7 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques
}
return
}
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(stored))
writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(stored))
}
// listAccountTaskRuns 负责list账号任务运行记录相关处理。
@@ -76,12 +73,12 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
return
}
// runs、err 保存runs、err,供当前处理流程使用
runs, err := s.communicationApplication().ListAccountTaskRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
runs, err := s.accountTaskApplication().ListRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
return
}
writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newAccountTaskRunResponses(runs)})
writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newApplicationAccountTaskRunResponses(runs)})
}
// runAccountTask 负责运行账号任务相关处理。
@@ -97,22 +94,26 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
return
}
// input 保存input,供当前处理流程使用
var input struct {
TaskType string `json:"task_type"`
}
if decodeJSON(r, &input) != nil || (input.TaskType != automation.TaskAutoRate && input.TaskType != automation.TaskAutoPolish) {
var input accountTaskRunRequest
if decodeJSON(r, &input) != nil || (input.TaskType != automationapp.TaskAutoRate && input.TaskType != automationapp.TaskAutoPolish) {
writeErr(w, http.StatusBadRequest, "不支持的任务类型")
return
}
// summary、err 保存summary、err,供当前处理流程使用
summary, err := s.communicationApplication().RunAccountTask(r.Context(), cid, input.TaskType)
summary, err := s.accountTaskApplication().Run(r.Context(), cid, input.TaskType)
if err != nil {
if errors.Is(err, errCommunicationUnavailable) {
if errors.Is(err, automationapp.ErrUnavailable) {
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
return
}
writeErr(w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, accountTaskRunResponseEnvelope{Success: true, Summary: newAccountTaskSummaryResponse(summary)})
writeJSON(w, http.StatusOK, accountTaskRunResponseEnvelope{Success: true, Summary: newApplicationAccountTaskSummaryResponse(summary)})
}
// accountTaskRunRequest 是手动执行账号任务的具名 HTTP 请求 DTO。
type accountTaskRunRequest struct {
// TaskType 是要求执行的账号任务类型。
TaskType string `json:"task_type"`
}
+2 -2
View File
@@ -296,9 +296,9 @@ func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
// TestChangeAdminPasswordNonAdmin 非 admin 403。
func TestChangeAdminPasswordNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
// h 保存h,供当前处理流程使用
h := srv.Router()
// body 保存请求体,供当前处理流程使用
+17 -13
View File
@@ -1,10 +1,12 @@
package server
import (
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
adminapp "xianyu-go/internal/application/admin"
)
// mountAdminReal 管理员端点。
@@ -18,7 +20,7 @@ func (s *Server) mountAdminReal(r chi.Router) {
// adminListUsers 负责adminList用户列表相关处理。
func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Admin.ListUsers(r.Context())
rows, err := s.applicationServiceSet().admin.ListUsers(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -44,21 +46,23 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "无效用户ID")
return
}
// 不允许删除自己。
// 不允许删除自己;应用服务统一执行该业务规则。
sess := authSess(r)
if sess.UserID == uid {
writeErr(w, http.StatusBadRequest, "不能删除当前登录用户")
return
}
if s.Manager != nil {
if accountIDs, listErr := s.Store.Cookies.ListOwnedIDs(r.Context(), uid); listErr == nil { // accountIDs 是待停止的账号 ID。
// accountIDs、listErr 保存应用服务返回的待停止账号 ID 列表及查询错误。
if accountIDs, listErr := s.accountSummaryApplication().ListOwnedIDs(r.Context(), uid); listErr == nil {
// cookieID 表示待停止运行实例的账号标识。
for _, cookieID := range accountIDs {
s.Manager.Stop(cookieID)
}
}
}
if // err 保存err,供当前处理流程使用
err := s.Store.Users.Delete(r.Context(), uid); err != nil {
// err 保存管理员删除应用用例的执行结果。
if err := s.applicationServiceSet().admin.DeleteUser(r.Context(), sess.UserID, uid); err != nil {
if errors.Is(err, adminapp.ErrSelfDelete) {
writeErr(w, http.StatusBadRequest, "不能删除当前登录用户")
return
}
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
@@ -67,8 +71,8 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
// adminListCookies 负责adminListCookies相关处理。
func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Admin.ListCookies(r.Context())
// rows、err 保存应用服务返回的管理员账号摘要及查询错误。
rows, err := s.accountSummaryApplication().ListAdminSummaries(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -80,7 +84,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
out = append(out, adminCookieResponse{
ID: row.ID, UserID: row.UserID, Remark: row.Remark,
CreatedAt: row.CreatedAt, Owner: row.Owner,
Enabled: s.Store.Cookies.GetStatus(r.Context(), row.ID),
Enabled: row.Enabled,
})
}
writeJSON(w, http.StatusOK, out)
@@ -89,7 +93,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
// adminStats 负责adminStats相关处理。
func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
// stats 是管理员仪表盘的数据库聚合结果。
stats, err := s.Store.Admin.Stats(r.Context())
stats, err := s.applicationServiceSet().admin.Stats(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计数据失败")
return
+82 -142
View File
@@ -2,83 +2,64 @@ package server
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
analyticsapp "xianyu-go/internal/application/analytics"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountAnalyticsReal 订单分析端点(仪表盘 BI 报表用)。
// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。
func (s *Server) analyticsApplication() *analyticsapp.Service {
return s.applicationServiceSet().analytics
}
// mountAnalyticsReal 挂载订单分析端点(仪表盘 BI 报表使用)。
func (s *Server) mountAnalyticsReal(r chi.Router) {
r.Get("/dashboard/stats", s.dashboardStats)
r.Get("/analytics/orders", s.orderAnalytics)
r.Get("/analytics/orders/valid", s.validOrders)
}
// dashboardStats 返回当前登录用户的数据概览。管理员全局统计仍由 /admin/stats 提供,
// 避免普通用户访问管理员接口,也避免把全局资源数和用户自己的订单收益混在一起。
// dashboardStats 负责dashboardStats相关处理。
// dashboardStats 返回当前登录用户的数据概览;管理员全局统计由 /admin/stats 提供。
func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) {
// sess 是当前请求的认证会话。
sess := auth.SessionFromContext(r.Context())
// result 和 err 是订单分析应用服务返回的仪表盘摘要。
// result 和 err 是订单分析应用服务返回的仪表盘摘要及错误。
result, err := s.analyticsApplication().DashboardStats(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计数据失败")
return
}
writeJSON(w, http.StatusOK, result)
writeJSON(w, http.StatusOK, dashboardStatsResponseFromApplication(result))
}
// 有效订单状态只统计以下几种。
var validOrderStatuses = []string{"pending_ship", "paid", "2", "shipped", "3", "completed", "4", "11"}
// orderAnalytics 汇总指定日期范围内的收益以及按日、状态、城市和商品分布。
func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
// sess 是当前请求的认证会话。
sess := auth.SessionFromContext(r.Context())
// startDate、endDate 和 location 是订单分析的日期范围及时区参数。
startDate := r.URL.Query().Get("start_date")
// endDate 保存结束日期,供当前处理流程使用
endDate := r.URL.Query().Get("end_date")
// location 保存地址,供当前处理流程使用
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
// where 和 params 是按用户、日期和状态归一化后的查询条件。
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
// amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。
amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "amount")
// result 和 err 是订单分析应用服务返回的具名统计结果。
result, err := s.analyticsApplication().OrderAnalytics(r.Context(), analyticsQuery{
Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter, Location: location,
})
// query 是从 HTTP 查询参数映射出的订单分析用例请求。
query := analyticsapp.Query{
UserID: sess.UserID, StartDate: r.URL.Query().Get("start_date"), EndDate: r.URL.Query().Get("end_date"),
Location: analyticsapp.LocationFromOffset(r.URL.Query().Get("timezone_offset_minutes")),
}
// result 和 err 是订单分析应用服务返回的统计结果及错误。
result, err := s.analyticsApplication().OrderAnalytics(r.Context(), query)
if err != nil {
writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err))
writeErr(w, http.StatusInternalServerError, analyticsapp.ErrorMessage(err))
return
}
writeJSON(w, http.StatusOK, result)
writeJSON(w, http.StatusOK, orderAnalyticsResponseFromApplication(result))
}
// validOrders 有效订单明细列表(用于统计中的订单明细)。
// validOrders 返回有效订单明细分页结果。
func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
// sess 是当前请求的认证会话。
sess := auth.SessionFromContext(r.Context())
// startDate、endDate 和 location 是有效订单的日期范围及时区参数。
startDate := r.URL.Query().Get("start_date")
// endDate 保存结束日期,供当前处理流程使用
endDate := r.URL.Query().Get("end_date")
// location 保存地址,供当前处理流程使用
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
// where 和 params 是按用户、日期和状态归一化后的查询条件。
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
// amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。
amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "orders.amount")
// page 和 pageSize 是已经限制在安全范围内的分页参数。
page := atoiDefault(r.URL.Query().Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
// pageSize 是每页返回的最大订单数量。
pageSize := atoiDefault(r.URL.Query().Get("page_size"), 500)
if page < 1 {
page = 1
@@ -86,120 +67,79 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
if pageSize < 1 || pageSize > 500 {
pageSize = 500
}
// result 和 err 是订单分析应用服务返回的分页结果。
result, err := s.analyticsApplication().ValidOrders(r.Context(), analyticsQuery{
Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter,
}, page, pageSize)
// query 是从 HTTP 查询参数映射出的有效订单用例请求。
query := analyticsapp.Query{
UserID: sess.UserID, StartDate: r.URL.Query().Get("start_date"), EndDate: r.URL.Query().Get("end_date"),
Location: analyticsapp.LocationFromOffset(r.URL.Query().Get("timezone_offset_minutes")),
}
// result 和 err 是订单分析应用服务返回的分页结果及错误。
result, err := s.analyticsApplication().ValidOrders(r.Context(), query, page, pageSize)
if err != nil {
writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err))
writeErr(w, http.StatusInternalServerError, analyticsapp.ErrorMessage(err))
return
}
writeJSON(w, http.StatusOK, result)
writeJSON(w, http.StatusOK, validOrdersResponseFromApplication(result))
}
// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。
// 返回 (whereClause, params),whereClause 已含 WHERE 前缀。
// buildAnalyticsWhere 负责buildAnalyticsWhere相关处理。
func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []string, location *time.Location) (string, []any) {
// conds 保存conds,供当前处理流程使用
conds := []string{"orders.deleted_at IS NULL"}
// params 保存params,供当前处理流程使用
params := []any{}
if startDate != "" {
conds = append(conds, "orders.created_at >= ?")
params = append(params, analyticsDateBoundary(startDate, false, location))
}
if endDate != "" {
conds = append(conds, "orders.created_at < ?")
params = append(params, analyticsDateBoundary(endDate, true, location))
}
if userID != 0 {
conds = append(conds, "EXISTS (SELECT 1 FROM cookies WHERE cookies.id = orders.cookie_id AND cookies.user_id = ?)")
params = append(params, userID)
}
if len(statuses) > 0 {
// ph 保存ph,供当前处理流程使用
ph := strings.Repeat("?,", len(statuses))
ph = strings.TrimSuffix(ph, ",")
conds = append(conds, "orders.order_status IN ("+ph+")")
// s 表示当前遍历过程中的s
for _, s := range statuses {
params = append(params, s)
}
}
// where 保存where,供当前处理流程使用
where := ""
if len(conds) > 0 {
where = "WHERE " + strings.Join(conds, " AND ")
}
// 后续 AND 需要前置空格。
if where != "" {
where += " "
}
return where, params
}
// analyticsDateBoundary 负责analytics日期Boundary相关处理。
// analyticsDateBoundary 保留日期边界测试使用的应用层转换入口。
func analyticsDateBoundary(raw string, endExclusive bool, location *time.Location) string {
if location == nil {
location = time.Local
}
// t、err 保存t、err,供当前处理流程使用
t, err := time.ParseInLocation("2006-01-02", strings.TrimSpace(raw), location)
if err != nil {
return raw
}
if endExclusive {
t = t.AddDate(0, 0, 1)
}
return t.UTC().Format("2006-01-02 15:04:05")
return analyticsapp.DateBoundary(raw, endExclusive, location)
}
// analyticsLocation 负责analytics地址相关处理。
func analyticsLocation(rawOffset string) *time.Location {
// offset、err 保存offset、err,供当前处理流程使用
offset, err := strconv.Atoi(strings.TrimSpace(rawOffset))
if err != nil || offset < -14*60 || offset > 14*60 {
return time.Local
}
return time.FixedZone("browser", offset*60)
}
// analyticsAmountExpression 负责analyticsAmountExpression相关处理。
func analyticsAmountExpression(dialect db.Dialect, column string) string {
// clean 保存clean,供当前处理流程使用
clean := `TRIM(REPLACE(REPLACE(` + column + `, '¥', ''), ',', ''))`
switch dialect {
case db.DialectPostgres:
return `CASE WHEN ` + clean + ` ~ '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE PRECISION) END`
case db.DialectMySQL:
return `CASE WHEN ` + clean + ` REGEXP '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE) END`
default:
return `CASE WHEN ` + clean + ` GLOB '[0-9]*' AND ` + clean + ` NOT GLOB '*[^0-9.]*' AND ` + clean + ` NOT GLOB '*.*.*' AND ` + clean + ` NOT LIKE '%.' THEN CAST(` + clean + ` AS REAL) END`
// dashboardStatsResponseFromApplication 将应用摘要映射为 HTTP DTO。
func dashboardStatsResponseFromApplication(result analyticsapp.DashboardStats) dashboardStatsResponse {
return dashboardStatsResponse{
TotalCookies: result.TotalCookies, ActiveCookies: result.ActiveCookies, TotalCards: result.TotalCards,
AvailableCardStock: result.AvailableCardStock, TotalKeywords: result.TotalKeywords, TotalOrders: result.TotalOrders,
}
}
// parseAnalyticsDBTime 负责parseAnalyticsDB时间相关处理。
func parseAnalyticsDBTime(raw string) time.Time {
// layout 表示当前遍历过程中的layout
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"} {
if // t、err 保存t、err,供当前处理流程使用
t, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC); err == nil {
return t
}
// orderAnalyticsResponseFromApplication 将应用统计映射为 HTTP DTO。
func orderAnalyticsResponseFromApplication(result analyticsapp.OrderAnalytics) orderAnalyticsResponse {
// dailyStats 是应用层按日结果对应的传输 DTO 列表。
dailyStats := make([]analyticsDailyStatsResponse, 0, len(result.DailyStats))
// item 是当前按日统计结果。
for _, item := range result.DailyStats {
dailyStats = append(dailyStats, analyticsDailyStatsResponse{Date: item.Date, OrderCount: item.OrderCount, Amount: item.Amount})
}
// statusStats 是应用层按状态结果对应的传输 DTO 列表。
statusStats := make([]analyticsStatusStatsResponse, 0, len(result.StatusStats))
// item 是当前按状态统计结果。
for _, item := range result.StatusStats {
statusStats = append(statusStats, analyticsStatusStatsResponse{Status: item.Status, Count: item.Count, Amount: item.Amount})
}
// cityStats 是应用层按城市结果对应的传输 DTO 列表。
cityStats := make([]analyticsCityStatsResponse, 0, len(result.CityStats))
// item 是当前按城市统计结果。
for _, item := range result.CityStats {
cityStats = append(cityStats, analyticsCityStatsResponse{City: item.City, OrderCount: item.OrderCount, TotalAmount: item.TotalAmount})
}
// itemStats 是应用层按商品结果对应的传输 DTO 列表。
itemStats := make([]analyticsItemStatsResponse, 0, len(result.ItemStats))
// item 是当前按商品统计结果。
for _, item := range result.ItemStats {
itemStats = append(itemStats, analyticsItemStatsResponse{ItemID: item.ItemID, OrderCount: item.OrderCount, TotalAmount: item.TotalAmount, AvgAmount: item.AvgAmount})
}
return orderAnalyticsResponse{
RevenueStats: analyticsRevenueStatsResponse{
TotalOrders: result.RevenueStats.TotalOrders, TotalAmount: result.RevenueStats.TotalAmount,
AvgAmount: result.RevenueStats.AvgAmount, UniqueBuyers: result.RevenueStats.UniqueBuyers, UniqueItems: result.RevenueStats.UniqueItems,
},
DailyStats: dailyStats, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats,
}
return time.Time{}
}
// parseAnalyticsAmount 负责parseAnalyticsAmount相关处理。
func parseAnalyticsAmount(raw string) float64 {
raw = strings.TrimSpace(strings.NewReplacer("¥", "", ",", "").Replace(raw))
// value 保存值,供当前处理流程使用
value, _ := strconv.ParseFloat(raw, 64)
return value
}
// round2 负责round2相关处理。
func round2(f float64) float64 {
return float64(int(f*100+0.5)) / 100
// validOrdersResponseFromApplication 将应用分页结果映射为 HTTP DTO。
func validOrdersResponseFromApplication(result analyticsapp.ValidOrders) validOrdersResponse {
// orders 是应用层有效订单对应的传输 DTO 列表。
orders := make([]validOrderResponse, 0, len(result.Orders))
// item 是当前有效订单应用模型。
for _, item := range result.Orders {
orders = append(orders, validOrderResponse{
OrderID: item.OrderID, ItemID: item.ItemID, BuyerID: item.BuyerID, ItemTitle: item.ItemTitle,
ItemImage: item.ItemImage, Quantity: item.Quantity, Amount: item.Amount, OrderStatus: item.OrderStatus,
Status: item.Status, CookieID: item.CookieID, CreatedAt: item.CreatedAt,
})
}
return validOrdersResponse{Orders: orders, Total: result.Total, Page: result.Page, PageSize: result.PageSize, Truncated: result.Truncated}
}
-57
View File
@@ -1,57 +0,0 @@
package server
import (
"context"
"database/sql"
"xianyu-go/internal/db"
)
// analyticsRepository 定义分析服务执行只读 SQL、读取卡密库存和获取数据库方言所需的最小能力。
type analyticsRepository interface {
// QueryRowContext 执行返回单行结果的分析查询。
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
// QueryContext 执行返回多行结果的分析查询。
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// ListCardsForUser 返回用户拥有的卡密组。
ListCardsForUser(ctx context.Context, userID int64) ([]db.CardFull, error)
// Dialect 返回当前数据库方言。
Dialect() db.Dialect
}
// storeAnalyticsRepository 将完整 Store 适配为分析服务窄 repository。
type storeAnalyticsRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// QueryRowContext 委托单行分析查询。
func (r storeAnalyticsRepository) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row {
return r.store.Analytics.QueryRowContext(ctx, query, args...)
}
// QueryContext 委托多行分析查询。
func (r storeAnalyticsRepository) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
return r.store.Analytics.QueryContext(ctx, query, args...)
}
// ListCardsForUser 委托用户卡密组查询。
func (r storeAnalyticsRepository) ListCardsForUser(ctx context.Context, userID int64) ([]db.CardFull, error) {
return r.store.Cards.AllForUser(ctx, userID)
}
// Dialect 返回 Store 使用的数据库方言。
func (r storeAnalyticsRepository) Dialect() db.Dialect {
return r.store.Dialect
}
// newStoreAnalyticsRepository 从完整 Store 构造分析服务窄 repository。
func newStoreAnalyticsRepository(store *db.Store) analyticsRepository {
if store == nil || store.Analytics == nil || store.Cards == nil {
return nil
}
return storeAnalyticsRepository{store: store}
}
// 确保 Store 适配器始终覆盖分析服务所需的全部能力。
var _ analyticsRepository = storeAnalyticsRepository{}
-397
View File
@@ -1,397 +0,0 @@
package server
import (
"context"
"errors"
"sort"
"strings"
"time"
"xianyu-go/internal/db"
)
// analyticsQuery 描述订单分析查询已经归一化的数据库过滤条件。
type analyticsQuery struct {
// Where 是包含 WHERE 前缀的订单过滤子句。
Where string
// Params 是 Where 对应的数据库参数。
Params []any
// AmountClean 是按数据库方言生成的金额表达式。
AmountClean string
// AmountFilter 是排除非法金额后的附加条件。
AmountFilter string
// Location 是用户选择的本地时区。
Location *time.Location
}
// analyticsStage 标识订单分析失败的查询阶段。
type analyticsStage string
const (
// analyticsStageRevenue 表示收益汇总查询失败。
analyticsStageRevenue analyticsStage = "revenue"
// analyticsStageDaily 表示每日统计查询失败。
analyticsStageDaily analyticsStage = "daily"
// analyticsStageStatus 表示状态统计查询失败。
analyticsStageStatus analyticsStage = "status"
// analyticsStageCity 表示城市统计查询失败。
analyticsStageCity analyticsStage = "city"
// analyticsStageItem 表示商品统计查询失败。
analyticsStageItem analyticsStage = "item"
// analyticsStageValidCount 表示有效订单总数查询失败。
analyticsStageValidCount analyticsStage = "valid_count"
// analyticsStageValidRows 表示有效订单明细查询失败。
analyticsStageValidRows analyticsStage = "valid_rows"
)
// analyticsServiceError 保留订单分析失败阶段,供 HTTP 层映射兼容错误消息。
type analyticsServiceError struct {
// stage 是失败的查询阶段。
stage analyticsStage
// err 是底层数据库错误。
err error
}
// Error 返回订单分析错误文本。
func (e *analyticsServiceError) Error() string { return e.err.Error() }
// Unwrap 暴露底层数据库错误。
func (e *analyticsServiceError) Unwrap() error { return e.err }
// analyticsService 承载订单分析的数据库编排,不依赖 HTTP 请求或响应对象。
type analyticsService struct {
// repository 提供分析查询、卡密库存和数据库方言能力。
repository analyticsRepository
}
// DashboardStats 查询当前用户的数据概览和可用卡密库存。
func (svc *analyticsService) DashboardStats(ctx context.Context, userID int64) (dashboardStatsResponse, error) {
// counts 保存仪表盘各项计数。
counts := map[string]int64{"total_cookies": 0, "active_cookies": 0, "total_cards": 0, "available_card_stock": 0, "total_keywords": 0, "total_orders": 0}
// queries 保存用户范围内的固定统计查询。
queries := []struct {
query string
key string
}{
{`SELECT COUNT(*) FROM cookies WHERE user_id=?`, "total_cookies"},
{`SELECT COUNT(*) FROM cards WHERE user_id=?`, "total_cards"},
{`SELECT COUNT(*) FROM keywords k WHERE EXISTS (SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`, "total_keywords"},
{`SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`, "total_orders"},
}
// item 是当前固定统计查询。
for _, item := range queries {
// count 是当前统计项的数据库结果。
var count int64
// err 是当前统计项查询错误。
if err := svc.repository.QueryRowContext(ctx, item.query, userID).Scan(&count); err != nil {
return dashboardStatsResponse{}, err
}
counts[item.key] = count
}
// activeCookies 是没有明确禁用记录的账号数量。
var activeCookies int64
// err 是活跃账号统计查询错误。
if err := svc.repository.QueryRowContext(ctx, `
SELECT COUNT(*) FROM cookies c WHERE c.user_id=?
AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
`, userID).Scan(&activeCookies); err != nil {
return dashboardStatsResponse{}, err
}
counts["active_cookies"] = activeCookies
// cards 和 err 是当前用户的卡密组列表及查询错误。
cards, err := svc.repository.ListCardsForUser(ctx, userID)
if err != nil {
return dashboardStatsResponse{}, err
}
// card 是当前遍历到的卡密组。
for _, card := range cards {
if !card.Enabled || card.Type != "data" {
continue
}
// line 是卡密组内容中的一行卡密。
for _, line := range strings.Split(strings.ReplaceAll(card.DataContent, "\r\n", "\n"), "\n") {
if strings.TrimSpace(line) != "" {
counts["available_card_stock"]++
}
}
}
return dashboardStatsResponse{TotalCookies: counts["total_cookies"], ActiveCookies: counts["active_cookies"], TotalCards: counts["total_cards"], AvailableCardStock: counts["available_card_stock"], TotalKeywords: counts["total_keywords"], TotalOrders: counts["total_orders"]}, nil
}
// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。
func (s *Server) analyticsApplication() *analyticsService {
return s.applicationServiceSet().analytics
}
// OrderAnalytics 查询收益及按日、状态、城市和商品维度聚合的订单分析结果。
func (svc *analyticsService) OrderAnalytics(ctx context.Context, query analyticsQuery) (orderAnalyticsResponse, error) {
// amountFilter 是已经排除非法金额的查询条件。
amountFilter := query.AmountFilter
// revenue 保存订单收益汇总结果。
var revenue analyticsRevenueStatsResponse
// err 是收益汇总查询错误。
if err := svc.repository.QueryRowContext(ctx, `
SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0),
COALESCE(AVG(`+query.AmountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id)
FROM orders `+query.Where+amountFilter, query.Params...).Scan(
&revenue.TotalOrders, &revenue.TotalAmount, &revenue.AvgAmount, &revenue.UniqueBuyers, &revenue.UniqueItems); err != nil {
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageRevenue, err: err}
}
// daily 保存按用户本地日期聚合的统计结果。
daily := make([]analyticsDailyStatsResponse, 0)
// rows 和 err 是每日统计查询结果集及错误。
rows, err := svc.repository.QueryContext(ctx, `
SELECT order_id,amount,created_at FROM orders `+query.Where+amountFilter, query.Params...)
if err != nil {
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err}
}
// dailyValue 保存同一天的订单数和金额累计值。
type dailyValue struct {
count int
amount float64
}
// dailyMap 按日期聚合订单数据,避免依赖数据库方言的日期函数。
dailyMap := map[string]dailyValue{}
for rows.Next() {
// orderID、amountRaw 和 createdAt 是当前订单的原始字段。
var orderID, amountRaw, createdAt string
if rows.Scan(&orderID, &amountRaw, &createdAt) != nil {
continue
}
// created 是转换后的订单创建时间。
created := parseAnalyticsDBTime(createdAt)
if created.IsZero() {
continue
}
// date 是订单在用户时区中的日期。
if query.Location != nil {
created = created.In(query.Location)
}
// date 是订单在用户时区中的日期。
date := created.Format("2006-01-02")
// value 是当前日期的累计统计值。
value := dailyMap[date]
value.count++
value.amount += parseAnalyticsAmount(amountRaw)
dailyMap[date] = value
}
// err 是每日统计游标迭代错误。
if err := rows.Err(); err != nil {
_ = rows.Close()
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err}
}
_ = rows.Close()
// dates 是排序后的日期列表。
dates := make([]string, 0, len(dailyMap))
// date 是当前待排序的日期。
for date := range dailyMap {
dates = append(dates, date)
}
sort.Strings(dates)
// date 是当前输出日期。
for _, date := range dates {
// value 是当前日期的累计统计值。
value := dailyMap[date]
daily = append(daily, analyticsDailyStatsResponse{Date: date, OrderCount: value.count, Amount: round2(value.amount)})
}
// statusStats 保存按订单状态聚合的结果。
statusStats := make([]analyticsStatusStatsResponse, 0)
// statusValue 保存单个状态的累计统计值。
type statusValue struct {
count int
amount float64
}
// statusMap 按归一化状态聚合订单数据。
statusMap := map[string]statusValue{}
// rows 和 err 是状态统计查询结果集及错误。
rows, err = svc.repository.QueryContext(ctx, `
SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0)
FROM orders `+query.Where+amountFilter+`
GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, query.Params...)
if err != nil {
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err}
}
for rows.Next() {
// status、count 和 amount 是当前状态的数据库聚合值。
var status string
// count 和 amount 是当前状态的订单数和金额。
var count int
// amount 是当前状态的订单金额。
var amount float64
if rows.Scan(&status, &count, &amount) == nil {
status = db.NormalizeOrderStatus(status)
// value 是当前状态的累计统计值。
value := statusMap[status]
value.count += count
value.amount += amount
statusMap[status] = value
}
}
// err 是状态统计游标迭代错误。
if err := rows.Err(); err != nil {
_ = rows.Close()
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err}
}
_ = rows.Close()
// statusNames 是按订单数量降序排列的状态名称。
statusNames := make([]string, 0, len(statusMap))
// status 是当前待排序的状态名称。
for status := range statusMap {
statusNames = append(statusNames, status)
}
sort.Slice(statusNames, func(i, j int) bool { return statusMap[statusNames[i]].count > statusMap[statusNames[j]].count })
// status 是当前输出状态。
for _, status := range statusNames {
// value 是当前状态的累计统计值。
value := statusMap[status]
statusStats = append(statusStats, analyticsStatusStatsResponse{Status: status, Count: value.count, Amount: round2(value.amount)})
}
// cityStats 保存按收货城市聚合的结果。
cityStats := make([]analyticsCityStatsResponse, 0)
// rows 和 err 是城市统计查询结果集及错误。
rows, err = svc.repository.QueryContext(ctx, `
SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0)
FROM orders `+query.Where+amountFilter+`
AND receiver_city IS NOT NULL AND receiver_city != ''
GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, query.Params...)
if err != nil {
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err}
}
for rows.Next() {
// city、count 和 amount 是当前城市的数据库聚合值。
var city string
// count 和 amount 是当前城市的订单数和金额。
var count int
// amount 是当前城市的订单金额。
var amount float64
if rows.Scan(&city, &count, &amount) == nil {
cityStats = append(cityStats, analyticsCityStatsResponse{City: city, OrderCount: count, TotalAmount: round2(amount)})
}
}
// err 是城市统计游标迭代错误。
if err := rows.Err(); err != nil {
_ = rows.Close()
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err}
}
_ = rows.Close()
// itemStats 保存按商品标识聚合的排行结果。
itemStats := make([]analyticsItemStatsResponse, 0)
// rows 和 err 是商品统计查询结果集及错误。
rows, err = svc.repository.QueryContext(ctx, `
SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0), COALESCE(AVG(`+query.AmountClean+`),0)
FROM orders `+query.Where+amountFilter+`
AND item_id IS NOT NULL AND item_id != ''
GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, query.Params...)
if err != nil {
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err}
}
for rows.Next() {
// itemID、count、total 和 average 是当前商品的数据库聚合值。
var itemID string
// count、total 和 average 是当前商品的订单数、总金额和平均金额。
var count int
// total 和 average 是当前商品的总金额和平均金额。
var total, average float64
if rows.Scan(&itemID, &count, &total, &average) == nil {
itemStats = append(itemStats, analyticsItemStatsResponse{ItemID: itemID, OrderCount: count, TotalAmount: round2(total), AvgAmount: round2(average)})
}
}
// err 是商品统计游标迭代错误。
if err := rows.Err(); err != nil {
_ = rows.Close()
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err}
}
_ = rows.Close()
return orderAnalyticsResponse{
RevenueStats: analyticsRevenueStatsResponse{
TotalOrders: revenue.TotalOrders, TotalAmount: round2(revenue.TotalAmount), AvgAmount: round2(revenue.AvgAmount),
UniqueBuyers: revenue.UniqueBuyers, UniqueItems: revenue.UniqueItems,
},
DailyStats: daily, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats,
}, nil
}
// ValidOrders 查询有效订单分页明细。
func (svc *analyticsService) ValidOrders(ctx context.Context, query analyticsQuery, page, pageSize int) (validOrdersResponse, error) {
// amountFilter 是已经排除非法金额的查询条件。
amountFilter := query.AmountFilter
// total 是符合筛选条件的订单总数。
var total int
// err 是有效订单总数查询错误。
if err := svc.repository.QueryRowContext(ctx, `SELECT COUNT(*) FROM orders `+query.Where+amountFilter, query.Params...).Scan(&total); err != nil {
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidCount, err: err}
}
// queryParams 是分页查询附加的 LIMIT/OFFSET 参数。
queryParams := append(append([]any{}, query.Params...), pageSize, (page-1)*pageSize)
// rows 和 err 是有效订单明细查询结果集及错误。
rows, err := svc.repository.QueryContext(ctx, `
SELECT orders.order_id, COALESCE(orders.item_id,''), COALESCE(item_info.item_title,''),
COALESCE(item_info.item_detail,''), COALESCE(orders.buyer_id,''), COALESCE(orders.quantity,'1'),
orders.amount, COALESCE(orders.order_status,'unknown'), COALESCE(orders.cookie_id,''), orders.created_at
FROM orders LEFT JOIN item_info ON item_info.cookie_id=orders.cookie_id AND item_info.item_id=orders.item_id
`+query.Where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, queryParams...)
if err != nil {
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err}
}
defer rows.Close()
// out 是有效订单响应列表。
out := make([]validOrderResponse, 0)
for rows.Next() {
// orderID、itemID、itemTitle、itemDetail、buyerID、quantity、amount、status、cookieID 和 createdAt 是订单字段。
var orderID, itemID, itemTitle, itemDetail, buyerID, quantity, amount, status, cookieID, createdAt string
if rows.Scan(&orderID, &itemID, &itemTitle, &itemDetail, &buyerID, &quantity, &amount, &status, &cookieID, &createdAt) == nil {
status = db.NormalizeOrderStatus(status)
out = append(out, validOrderResponse{OrderID: orderID, ItemID: itemID, BuyerID: buyerID, ItemTitle: itemTitle, ItemImage: itemImageFromDetail(itemDetail), Quantity: quantity, Amount: amount, OrderStatus: status, Status: status, CookieID: cookieID, CreatedAt: createdAt})
}
}
// err 是有效订单游标迭代错误。
if err := rows.Err(); err != nil {
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err}
}
return validOrdersResponse{Orders: out, Total: total, Page: page, PageSize: pageSize, Truncated: (page-1)*pageSize+len(out) < total}, nil
}
// analyticsStageOf 读取分析服务错误阶段。
func analyticsStageOf(err error) (analyticsStage, bool) {
// serviceErr 是带查询阶段的应用服务错误。
var serviceErr *analyticsServiceError
if !errors.As(err, &serviceErr) {
return "", false
}
return serviceErr.stage, true
}
// analyticsErrorMessage 将分析服务阶段映射为原有 HTTP 错误消息。
func analyticsErrorMessage(err error) string {
// stage 是应用服务错误对应的查询阶段。
switch stage, _ := analyticsStageOf(err); stage {
case analyticsStageRevenue:
return "查询收益统计失败"
case analyticsStageDaily:
return "查询每日统计失败"
case analyticsStageStatus:
return "查询状态统计失败"
case analyticsStageCity:
return "查询城市统计失败"
case analyticsStageItem:
return "查询商品统计失败"
default:
return "查询失败"
}
}
// analyticsQueryAmountFilter 根据订单分析查询构造金额过滤条件。
func analyticsQueryAmountFilter(store *db.Store, column string) (string, string) {
// clean 是按数据库方言清洗后的金额表达式。
clean := analyticsAmountExpression(store.Dialect, column)
return clean, " AND " + clean + " IS NOT NULL"
}
// analyticsQueryParamsCopy 复制查询参数,避免服务层修改 handler 持有的切片。
func analyticsQueryParamsCopy(params []any) []any {
return append([]any(nil), params...)
}
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"github.com/go-chi/chi/v5/middleware"
"xianyu-go/internal/db"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/httpapi"
)
@@ -98,7 +98,7 @@ func writeErrDetails(w http.ResponseWriter, status int, code, msg, requestID str
// writeCredentialVerificationError 将当前密码校验失败区分为认证失败或内部故障。
func writeCredentialVerificationError(w http.ResponseWriter, err error) {
if errors.Is(err, db.ErrPasswordMismatch) {
if errors.Is(err, accountapp.ErrPasswordMismatch) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
+2 -2
View File
@@ -152,14 +152,14 @@ func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, bod
// TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。
func TestAPIContractRemainingAuthenticationErrors(t *testing.T) {
// srv 是用于验证剩余认证错误边界的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// created 表示用于验证用户名冲突的占位用户是否成功创建。
created, createErr := srv.Store.Users.Create(context.Background(), "taken-user", "[email protected]", "pw")
created, createErr := store.Users.Create(context.Background(), "taken-user", "[email protected]", "pw")
if createErr != nil || !created {
t.Fatalf("create conflict user: created=%v err=%v", created, createErr)
}
+330 -22
View File
@@ -1,33 +1,71 @@
package server
import (
"context"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
adminapp "xianyu-go/internal/application/admin"
analyticsapp "xianyu-go/internal/application/analytics"
automationapp "xianyu-go/internal/application/automation"
cardsapp "xianyu-go/internal/application/cards"
chatapp "xianyu-go/internal/application/chat"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
itemapp "xianyu-go/internal/application/items"
keywordsapp "xianyu-go/internal/application/keywords"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
settingsapp "xianyu-go/internal/application/settings"
)
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
type applicationServices struct {
// orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。
orders *orderHTTPAdapter
// itemPublish 是商品发布应用服务。
itemPublish *itemPublishService
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
itemSinglePublish *itemapp.Service
// itemBatchRunner 是商品批量发布 worker 的应用层编排器。
itemBatchRunner *itemapp.BatchRunner
// itemBatchRecovery 是过期批量发布任务的租约接管应用服务。
itemBatchRecovery *itemapp.BatchRecoveryService
// itemBatchPreview 是商品批量发布表格预检应用服务。
itemBatchPreview *itemapp.BatchPreviewService
// itemBatchManagement 是商品批次查询、取消和重试应用服务。
itemBatchManagement *itemapp.BatchManagementService
// itemCategoryRecommendation 是商品类目推荐应用服务。
itemCategoryRecommendation *itemapp.CategoryRecommendationService
// itemBatchPreviewPersistence 是预检结果持久化应用服务。
itemBatchPreviewPersistence *itemapp.BatchPreviewPersistenceService
// itemBatchLocalPublish 是远端发布成功后的本地商品与规则收口服务。
itemBatchLocalPublish *itemapp.BatchLocalPublishService
// itemSync 是商品全量和分页同步应用服务。
itemSync *itemapp.SyncService
// itemCatalog 是商品列表和详情读取应用服务。
itemCatalog *itemapp.CatalogService
// itemCatalogMutation 是商品创建、更新、删除和交付开关应用服务。
itemCatalogMutation *itemapp.CatalogMutationService
// accountLogin 是账号登录应用服务。
accountLogin *accountLoginService
// authentication 是用户会话、密码校验和登录凭据应用服务。
authentication *accountapp.AuthenticationService
// loginAudit 是登录成功审计应用服务,负责方式归一化和账号启用编排。
loginAudit *accountapp.LoginAuditService
// passwordLogin 是密码登录策略应用服务;当前只返回关闭策略,不保存登录秘密或会话。
passwordLogin *accountapp.PasswordLoginService
// accountDelete 是账号删除应用服务,负责停止 fencing 和归属复核后的持久化删除。
accountDelete *accountapp.DeleteService
// accountProfile 是账号资料刷新应用服务。
accountProfile *accountapp.ProfileService
// communication 是聊天、通知和账号任务应用服务。
communication *communicationService
// accountLongLogin 是账号长登录设置应用服务。
accountLongLogin *accountapp.LongLoginService
// accountSettings 是账号设置、登录信息、启停和暂停应用服务。
accountSettings *accountapp.SettingsService
// accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。
accountSummaries *accountapp.SummaryService
// accountTasks 是账号任务设置、历史和手动执行应用服务。
accountTasks *automationapp.Service
// credentialWake 是凭证恢复后唤醒自动化任务的应用服务。
credentialWake *automationapp.CredentialWakeService
// chat 是聊天历史查询应用服务,负责用户归属和分页编排。
chat *chatapp.Service
// uncertainNotifications 是通知不确定状态运维查询应用服务。
@@ -35,37 +73,126 @@ type applicationServices struct {
// notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。
notificationChannels *notificationsapp.ChannelService
// analytics 是订单分析应用服务。
analytics *analyticsService
analytics *analyticsapp.Service
// automationIssues 是自动化异常查询与人工处理应用服务。
automationIssues *automationapp.IssueService
// automationRules 是自动化规则校验、分页和持久化应用服务。
automationRules *automationapp.RuleService
// cards 是卡券 CRUD、输入校验和所有权编排应用服务。
cards *cardsapp.Service
// publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。
publishAutomationRules *automationapp.PublishRuleService
// defaultReplies 是默认回复配置与投递记录应用服务。
defaultReplies *defaultreplyapp.Service
// keywords 是关键词规则与指定商品回复应用服务。
keywords *keywordsapp.Service
// settings 是系统、用户和账号 AI 设置应用服务。
settings *settingsapp.Service
// admin 是管理员用户管理与全局统计应用服务。
admin *adminapp.Service
}
// newApplicationServices 为指定 Server 装配全部应用服务实例。
func newApplicationServices(server *Server) *applicationServices {
// orderRepository 保存订单应用服务共享的基础设施适配器。
orderRepository := newStoreOrderRepository(server.Store)
orderRepository := server.dependencies.NewOrderRepository()
// orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。
orderReconciliation := server.dependencies.NewOrderReconciliationRepository()
// orderRuntime 保存订单服务共享的运行时能力适配器。
orderRuntime := newServerOrderRuntime(server)
orderRuntime := newServerOrderRuntime(server, orderReconciliation)
// orderServices 保存应用层统一构造的订单业务服务集合。
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, newStoreOrderRefreshJobRepository(server.Store), refreshOrderChunkSize)
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.dependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
// accountProfile 保存账号资料刷新用例的构造结果。
accountProfile, profileErr := newAccountProfileApplication(server)
// accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。
accountRepository := server.dependencies.NewAccountLoginRepository()
// accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, server.recoverExpiredMTOPSession, 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),
)
if longLoginErr != nil {
panic(longLoginErr)
}
// accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。
var settingsRuntime accountapp.SettingsRuntime
if server.Manager != nil {
settingsRuntime = server.Manager
}
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.dependencies.NewAccountSettingsRepository(), settingsRuntime)
if accountSettingsErr != nil {
panic(accountSettingsErr)
}
// accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。
accountSummaryRepository := server.dependencies.NewAccountSummaryRepository()
// accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。
accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository)
if accountSummariesErr != nil {
panic(accountSummariesErr)
}
// credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(server.dependencies.NewAutomationCredentialWakeRepository())
if credentialWakeErr != nil {
panic(credentialWakeErr)
}
// deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。
var deleteRuntime accountapp.DeleteRuntime
if server.Manager != nil {
deleteRuntime = server.Manager
}
// accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。
accountDelete, deleteErr := accountapp.NewDeleteService(storeAccountProfileRepository{store: server.Store}, deleteRuntime)
accountDelete, deleteErr := accountapp.NewDeleteService(accountRepository, deleteRuntime)
if deleteErr != nil {
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)
}, readBatchImageFile, downloadImageURL)
// itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。
itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService(
server.dependencies.NewItemBatchRepository(),
server.dependencies.NewItemCatalogRepository(),
server.dependencies.NewAutomationRepository(),
)
if itemBatchLocalPublishErr != nil {
panic(itemBatchLocalPublishErr)
}
// itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server)
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server, itemBatchPublish, itemBatchLocalPublish)
if batchRunnerErr != nil {
panic(batchRunnerErr)
}
// itemBatchRecovery 负责恢复扫描的批次状态编排,worker 启动仍由 Server 生命周期边界提供。
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)
},
},
)
if batchRecoveryErr != nil {
panic(batchRecoveryErr)
}
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
itemBatchPreviewPort := server.dependencies.NewItemBatchPreviewPort()
// itemBatchPreview 是批量发布预检应用服务的构造结果。
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
if itemBatchPreviewErr != nil {
panic(itemBatchPreviewErr)
}
// itemBatchManagement 是批次管理应用服务的构造结果。
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.dependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server})
if itemBatchManagementErr != nil {
panic(itemBatchManagementErr)
}
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(server)
if accountLoginCreateErr != nil {
@@ -73,50 +200,231 @@ func newApplicationServices(server *Server) *applicationServices {
}
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
var accountQRLogin *accountapp.QRLoginService
if server.Store != nil {
if server.dependencies != nil {
// accountQRLoginErr 保存扫码应用服务装配失败原因。
var accountQRLoginErr error
accountQRLogin, accountQRLoginErr = newAccountQRLoginApplication(server)
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.dependencies.NewQRLoginRepository(), serverQRLoginLifecycle{server: server})
if accountQRLoginErr != nil {
panic(accountQRLoginErr)
}
}
// automationRepository 复用同一个数据库适配器,保持自动化异常与规则查询的基础设施边界一致。
automationRepository := server.dependencies.NewAutomationRepository()
// settingsService 统一装配设置数据库与远端模型目录适配器。
settingsService := settingsapp.NewService(server.dependencies.NewSettingsRepository(), adapter.NewAIModelClient())
// adminService 负责管理员用户与仪表盘查询,HTTP 层只做 DTO 映射。
adminService := adminapp.NewService(server.dependencies.NewAdminRepository())
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
itemCatalogRepository := server.dependencies.NewItemCatalogRepository()
// itemCatalog 是商品列表和详情读取用例的应用服务。
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
if itemCatalogErr != nil {
panic(itemCatalogErr)
}
// itemCatalogMutation 是商品写入用例的应用服务。
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
if itemCatalogMutationErr != nil {
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)
})
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
if itemCategoryRecommendationErr != nil {
panic(itemCategoryRecommendationErr)
}
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.dependencies.NewItemBatchRepository())
if itemBatchPreviewPersistenceErr != nil {
panic(itemBatchPreviewPersistenceErr)
}
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
itemPublishPort,
server.dependencies.NewItemPublishRepository(),
)
if itemSinglePublishErr != nil {
panic(itemSinglePublishErr)
}
return &applicationServices{
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
itemSinglePublish: newItemPublishApplication(server),
itemBatchRunner: itemBatchRunner,
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
itemSinglePublish: itemSinglePublish,
itemBatchRunner: itemBatchRunner,
itemBatchRecovery: itemBatchRecovery,
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)
})),
itemCatalog: itemCatalog,
itemCatalogMutation: itemCatalogMutation,
accountLogin: &accountLoginService{server: server, repository: accountRepository, summaryRepository: accountSummaryRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin},
authentication: newAuthenticationApplication(server),
loginAudit: accountapp.NewLoginAuditService(server.dependencies.NewAccountLoginAuditRepository()),
passwordLogin: accountapp.NewPasswordLoginService(),
accountDelete: accountDelete,
accountProfile: accountProfile,
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
accountLongLogin: accountLongLogin,
accountSettings: accountSettings,
accountSummaries: accountSummaries,
accountTasks: automationapp.NewService(server.dependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)),
credentialWake: credentialWake,
chat: newChatSendingApplication(server),
uncertainNotifications: notificationsapp.New(newStoreNotificationUncertainRepository(server.Store)),
notificationChannels: notificationsapp.NewChannelService(newStoreNotificationChannelRepository(server.Store), server.notifier),
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
uncertainNotifications: notificationsapp.New(server.dependencies.NewNotificationUncertainRepository()),
notificationChannels: notificationsapp.NewChannelService(server.dependencies.NewNotificationChannelRepository(), server.notifier),
analytics: analyticsapp.NewService(server.dependencies.NewAnalyticsRepository()),
automationRules: automationapp.NewRuleService(automationRepository, automationRepository),
cards: cardsapp.NewService(server.dependencies.NewCardsRepository()),
publishAutomationRules: automationapp.NewPublishRuleService(automationRepository),
automationIssues: automationapp.NewIssueService(automationRepository),
defaultReplies: defaultreplyapp.NewService(server.dependencies.NewDefaultReplyRepository()),
keywords: keywordsapp.NewService(server.dependencies.NewKeywordRepository()),
settings: settingsService,
admin: adminService,
}
}
// newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。
func newAuthenticationApplication(server *Server) *accountapp.AuthenticationService {
// authentication、authenticationErr 保存认证应用服务及其装配错误。
authentication, authenticationErr := accountapp.NewAuthenticationService(server.dependencies.NewAuthenticationRepository())
if authenticationErr != nil {
panic(authenticationErr)
}
return authentication
}
// itemCatalogApplication 返回当前 Server 绑定的商品读取应用服务。
func (s *Server) itemCatalogApplication() *itemapp.CatalogService {
return s.applicationServiceSet().itemCatalog
}
// itemSinglePublishApplication 返回当前 Server 绑定的单商品发布应用服务。
func (s *Server) itemSinglePublishApplication() *itemapp.Service {
return s.applicationServiceSet().itemSinglePublish
}
// itemCatalogMutationApplication 返回当前 Server 绑定的商品写入应用服务。
func (s *Server) itemCatalogMutationApplication() *itemapp.CatalogMutationService {
return s.applicationServiceSet().itemCatalogMutation
}
// itemSyncApplication 返回当前 Server 绑定的商品同步应用服务。
func (s *Server) itemSyncApplication() *itemapp.SyncService {
return s.applicationServiceSet().itemSync
}
// cardsApplication 返回当前 Server 绑定的卡券 CRUD 应用服务。
func (s *Server) cardsApplication() *cardsapp.Service {
return s.applicationServiceSet().cards
}
// accountTaskApplication 返回当前 Server 绑定的账号任务应用服务。
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
}
// automationRulesApplication 返回当前 Server 绑定的自动化规则应用服务。
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
}
// itemBatchManagementApplication 返回当前 Server 绑定的批次管理应用服务。
func (s *Server) itemBatchManagementApplication() *itemapp.BatchManagementService {
return s.applicationServiceSet().itemBatchManagement
}
// itemCategoryRecommendationApplication 返回商品类目推荐应用服务。
func (s *Server) itemCategoryRecommendationApplication() *itemapp.CategoryRecommendationService {
return s.applicationServiceSet().itemCategoryRecommendation
}
// itemBatchPreviewPersistenceApplication 返回预检结果持久化应用服务。
func (s *Server) itemBatchPreviewPersistenceApplication() *itemapp.BatchPreviewPersistenceService {
return s.applicationServiceSet().itemBatchPreviewPersistence
}
// accountProfileApplication 返回当前 Server 绑定的账号资料应用服务。
func (s *Server) accountProfileApplication() *accountapp.ProfileService {
return s.applicationServiceSet().accountProfile
}
// accountLongLoginApplication 返回当前 Server 绑定的长登录应用服务。
func (s *Server) accountLongLoginApplication() *accountapp.LongLoginService {
return s.applicationServiceSet().accountLongLogin
}
// accountSettingsApplication 返回当前 Server 绑定的账号设置应用服务。
func (s *Server) accountSettingsApplication() *accountapp.SettingsService {
return s.applicationServiceSet().accountSettings
}
// authenticationApplication 返回当前 Server 绑定的用户认证应用服务。
func (s *Server) authenticationApplication() *accountapp.AuthenticationService {
return s.applicationServiceSet().authentication
}
// accountSummaryApplication 返回当前 Server 绑定的账号摘要应用服务。
func (s *Server) accountSummaryApplication() *accountapp.SummaryService {
return s.applicationServiceSet().accountSummaries
}
// accountDeleteApplication 返回当前 Server 绑定的账号删除应用服务。
func (s *Server) accountDeleteApplication() *accountapp.DeleteService {
return s.applicationServiceSet().accountDelete
}
// loginAuditApplication 返回当前 Server 绑定的登录成功审计应用服务。
func (s *Server) loginAuditApplication() *accountapp.LoginAuditService {
return s.applicationServiceSet().loginAudit
}
// settingsApplication 返回当前 Server 绑定的设置应用服务。
func (s *Server) settingsApplication() *settingsapp.Service {
return s.applicationServiceSet().settings
}
// applicationServiceSet 返回当前 Server 的应用服务集合,并兼容测试 Server。
func (s *Server) applicationServiceSet() *applicationServices {
if s == nil {
return &applicationServices{}
}
if s.applications != nil {
return s.applications
}
if s.dependencies == nil {
// accountLogin 仅用于零值 Server 的输入校验测试,不触发任何持久化访问。
return &applicationServices{accountLogin: &accountLoginService{server: s}}
}
return newApplicationServices(s)
}
+2 -2
View File
@@ -12,13 +12,13 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
}
// services 是统一应用服务集合。
services := srv.applicationServiceSet()
if services.orders == nil || services.itemPublish == nil || services.itemSinglePublish == nil || services.accountLogin == nil || services.passwordLogin == nil || services.accountDelete == nil || services.communication == nil || services.analytics == nil {
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 {
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 {
t.Fatal("订单应用服务应由应用层 ServiceSet 完整装配")
}
if srv.orders() != services.orders || srv.itemPublishApplication() != services.itemPublish || srv.accountLoginApplication() != services.accountLogin || srv.communicationApplication() != services.communication || srv.analyticsApplication() != services.analytics {
if srv.orders() != services.orders || srv.itemCatalogApplication() != services.itemCatalog || srv.itemCatalogMutationApplication() != services.itemCatalogMutation || srv.accountLoginApplication() != services.accountLogin || srv.analyticsApplication() != services.analytics || srv.defaultReplyApplication() != services.defaultReplies || srv.keywordApplication() != services.keywords {
t.Fatal("应用服务访问器未返回统一装配实例")
}
}
+21 -21
View File
@@ -8,8 +8,8 @@ import (
"time"
"unicode/utf8"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// loginRequest 是登录请求体。
@@ -53,7 +53,7 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
defer s.initializationMu.Unlock()
// initialized、err 保存initialized、err,供当前处理流程使用
initialized, err := s.Store.Users.IsSystemInitialized(r.Context())
initialized, err := s.authenticationApplication().IsSystemInitialized(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "检查系统初始化状态失败")
return
@@ -64,13 +64,13 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
}
if // err 保存err,供当前处理流程使用
_, err := auth.InitAdmin(r.Context(), s.Store, "[email protected]", req.Password); err != nil {
_, err := s.authenticationApplication().InitializeAdmin(r.Context(), "[email protected]", req.Password); err != nil {
writeErr(w, http.StatusInternalServerError, "初始化管理员失败")
return
}
// 初始化完成后立即建立会话,用户无需再手动输入一次 admin 账号和密码。
sid, user, err := s.Auth.Login(r.Context(), "admin", req.Password)
sid, user, err := s.authenticationApplication().Login(r.Context(), "admin", req.Password)
if err != nil || user == nil || sid == "" {
writeErr(w, http.StatusInternalServerError, "初始化完成,但自动登录失败,请使用 admin 账号登录")
return
@@ -108,7 +108,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
switch {
case req.Username != "" && req.Password != "":
// sid、user、err 保存sid、user、err,供当前处理流程使用
sid, user, err := s.Auth.Login(r.Context(), req.Username, req.Password)
sid, user, err := s.authenticationApplication().Login(r.Context(), req.Username, req.Password)
if err != nil || user == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
@@ -125,16 +125,16 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
return
case req.Email != "" && req.Password != "":
// user、err 保存user、err,供当前处理流程使用
user, err := s.Store.Users.GetByEmail(r.Context(), req.Email)
if err != nil || user == nil {
// username、err 保存邮箱映射得到的登录用户名和查询错误,供当前处理流程使用
username, err := s.authenticationApplication().UsernameByEmail(r.Context(), req.Email)
if err != nil || username == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
"邮箱或密码错误", "")
return
}
// sid、loginUser、lerr 保存sid、loginUser、lerr,供当前处理流程使用
sid, loginUser, lerr := s.Auth.Login(r.Context(), user.Username, req.Password)
sid, loginUser, lerr := s.authenticationApplication().Login(r.Context(), username, req.Password)
if lerr != nil || loginUser == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
@@ -160,7 +160,7 @@ func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
// ctx 保存ctx,供当前处理流程使用
ctx := r.Context()
// initialized 保存initialized,供当前处理流程使用
initialized, _ := s.Store.Users.IsSystemInitialized(ctx)
initialized, _ := s.authenticationApplication().IsSystemInitialized(ctx)
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(ctx)
if sess != nil {
@@ -215,13 +215,13 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
return
}
// 校验当前密码。
user, ok, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword)
if !ok || user == nil {
_, ok, _ := s.authenticationApplication().VerifyPassword(ctx, sess.Username, req.CurrentPassword)
if !ok {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
_, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
_, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -253,14 +253,14 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// user 保存用户,供当前处理流程使用
user, _, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword)
if user == nil {
// ok 保存当前密码是否匹配,应用层不会向 HTTP 层暴露密码哈希。
_, ok, _ := s.authenticationApplication().VerifyPassword(ctx, sess.Username, req.CurrentPassword)
if !ok {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
_, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
_, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -308,18 +308,18 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
return
}
// user、ok、err 保存user、ok、err,供当前处理流程使用
user, ok, err := s.Store.Users.VerifyAndUpgrade(r.Context(), sess.Username, req.CurrentPassword)
user, ok, err := s.authenticationApplication().VerifyPassword(r.Context(), sess.Username, req.CurrentPassword)
if err != nil {
writeCredentialVerificationError(w, err)
return
}
if !ok || user == nil || user.ID != sess.UserID {
if !ok || user.ID != sess.UserID {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
if errors.Is(err, db.ErrUsernameTaken) {
err := s.authenticationApplication().UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
if errors.Is(err, accountapp.ErrUsernameTaken) {
writeErrCode(w, http.StatusConflict, "username_taken", "用户名已被占用", "")
return
}
+44 -395
View File
@@ -1,7 +1,6 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"strconv"
@@ -9,9 +8,8 @@ import (
"github.com/go-chi/chi/v5"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
)
// mountAutomation 负责mount自动化相关处理。
@@ -30,12 +28,45 @@ func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// runs、tasks、err 保存runs、tasks、err,供当前处理流程使用
runs, tasks, err := s.Store.Automation.ListIssues(r.Context(), sess.UserID)
runs, tasks, err := s.automationIssuesApplication().ListIssues(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
return
}
writeJSON(w, http.StatusOK, automationIssuesResponse{Runs: runs, PendingTasks: tasks})
writeJSON(w, http.StatusOK, automationIssuesResponse{
Runs: automationRunIssueDTOs(runs),
PendingTasks: deferredAutomationIssueDTOs(tasks),
})
}
// automationRunIssueDTOs 将应用层自动化运行摘要转换为 HTTP DTO,避免响应直接暴露应用内部模型。
func automationRunIssueDTOs(issues []automationapp.RunIssue) []automationRunIssueDTO {
// result 是待写入响应的自动化运行 DTO 列表。
result := make([]automationRunIssueDTO, 0, len(issues))
// issue 是当前待转换的应用层运行异常摘要。
for _, issue := range issues {
result = append(result, automationRunIssueDTO{
ID: issue.ID, CookieID: issue.CookieID, OrderID: issue.OrderID,
TriggerType: issue.TriggerType, ErrorMessage: issue.ErrorMessage,
IssueKind: issue.IssueKind, AllowedResolutions: issue.AllowedResolutions,
ActionCursor: issue.ActionCursor, SentCount: issue.SentCount, UpdatedAt: issue.UpdatedAt,
})
}
return result
}
// deferredAutomationIssueDTOs 将应用层延期任务摘要转换为 HTTP DTO。
func deferredAutomationIssueDTOs(issues []automationapp.DeferredIssue) []deferredAutomationIssueDTO {
// result 是待写入响应的延期任务 DTO 列表。
result := make([]deferredAutomationIssueDTO, 0, len(issues))
// issue 是当前待转换的应用层延期异常摘要。
for _, issue := range issues {
result = append(result, deferredAutomationIssueDTO{
ID: issue.ID, CookieID: issue.CookieID, TriggerType: issue.TriggerType,
ErrorMessage: issue.ErrorMessage, AttemptCount: issue.AttemptCount, UpdatedAt: issue.UpdatedAt,
})
}
return result
}
// resolveAutomationRun 负责resolve自动化运行相关处理。
@@ -58,8 +89,8 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if errors.Is(err, db.ErrNotFound) {
err := s.automationIssuesApplication().ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if errors.Is(err, automationapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "异常运行不存在或已处理")
return
}
@@ -82,402 +113,20 @@ func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Re
Resolution string `json:"resolution"`
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || (req.Resolution != "retry" && req.Resolution != "dismiss") {
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "处理方式必须是 retry 或 dismiss")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution == "retry"); err != nil {
err := s.automationIssuesApplication().ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution); err != nil {
if errors.Is(err, automationapp.ErrInvalidDeferredResolution) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
writeErr(w, http.StatusNotFound, "异常任务不存在或已处理")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// automationActionRequest 保存自动化动作请求,供当前处理流程使用
type automationActionRequest struct {
ActionType string `json:"action_type"`
CardID int64 `json:"card_id"`
DeliveryCount int `json:"delivery_count"`
MessageTemplate string `json:"message_template"`
DelaySeconds int `json:"delay_seconds"`
ConfigJSON string `json:"config_json"`
Enabled *bool `json:"enabled"`
SortOrder int `json:"sort_order"`
}
// automationRuleRequest 保存自动化规则请求,供当前处理流程使用
type automationRuleRequest struct {
CookieID string `json:"cookie_id"`
ItemID string `json:"item_id"`
Name string `json:"name"`
TriggerType string `json:"trigger_type"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
ConfigJSON string `json:"config_json"`
Actions []automationActionRequest `json:"actions"`
}
// listAutomationRules 负责list自动化规则列表相关处理。
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// query 保存查询,供当前处理流程使用
query := r.URL.Query()
// paginated 保存paginated,供当前处理流程使用
_, paginated := query["page"]
if !paginated {
// rules、err 保存rules、err,供当前处理流程使用
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
writeJSON(w, http.StatusOK, automationRulesJSON(rules))
return
}
// page 保存页码,供当前处理流程使用
page := atoiDefault(query.Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
pageSize := atoiDefault(query.Get("page_size"), 10)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 10
}
if pageSize > 100 {
pageSize = 100
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := strings.TrimSpace(query.Get("cookie_id"))
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
}
// triggerType 保存trigger类型,供当前处理流程使用
triggerType := strings.TrimSpace(query.Get("trigger_type"))
if triggerType != "" {
switch triggerType {
case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout:
default:
writeErr(w, http.StatusBadRequest, "不支持的触发类型")
return
}
}
// enabled 保存启用状态,供当前处理流程使用
var enabled *bool
if // rawEnabled 保存原始启用状态,供当前处理流程使用
rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
// value、parseErr 保存value、parseErr,供当前处理流程使用
value, parseErr := strconv.ParseBool(rawEnabled)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
return
}
enabled = &value
}
// rules、total、err 保存rules、total、err,供当前处理流程使用
rules, total, err := s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
// filter 保存filter,供当前处理流程使用
filter := db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"),
}
// triggerCounts、err 保存triggerCounts、err,供当前处理流程使用
triggerCounts, err := s.Store.Automation.CountByTriggerForUser(r.Context(), filter)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计自动化规则失败")
return
}
// totalPages 保存总数Pages,供当前处理流程使用
totalPages := (total + pageSize - 1) / pageSize
if totalPages > 0 && page > totalPages {
page = totalPages
rules, _, err = s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
}
writeJSON(w, http.StatusOK, automationRulePageResponse{
Success: true, Data: automationRulesJSON(rules), Total: total, Page: page,
PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts,
})
}
// automationRulesJSON 负责自动化规则列表JSON相关处理。
func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse {
// out 保存out,供当前处理流程使用
out := make([]automationRuleResponse, 0, len(rules))
// rule 表示当前遍历过程中的规则
for _, rule := range rules {
// actions 保存动作列表,供当前处理流程使用
actions := make([]automationActionResponse, 0, len(rule.Actions))
// action 表示当前遍历过程中的动作
for _, action := range rule.Actions {
actions = append(actions, automationActionResponse{
ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName,
DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate,
DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled,
SortOrder: action.SortOrder,
})
}
out = append(out, automationRuleResponse{
ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle,
Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority,
ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt,
})
}
return out
}
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Automation.Create(r.Context(), in)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
return
}
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateAutomationRule 负责update自动化规则相关处理。
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
writeErr(w, http.StatusInternalServerError, "更新自动化规则失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAutomationRule 负责delete自动化规则相关处理。
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.Delete(r.Context(), sess.UserID, ruleID); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
if errors.Is(err, db.ErrAutomationRunActive) {
writeErr(w, http.StatusConflict, "规则仍有运行中或待人工处理的任务,处理完成后才能删除")
return
}
writeErr(w, http.StatusInternalServerError, "删除自动化规则失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// normalizeAutomationRuleRequest 负责normalize自动化规则请求相关处理。
func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) {
req.CookieID = strings.TrimSpace(req.CookieID)
req.ItemID = strings.TrimSpace(req.ItemID)
req.Name = strings.TrimSpace(req.Name)
req.TriggerType = strings.TrimSpace(req.TriggerType)
switch req.TriggerType {
case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout:
default:
return db.AutomationRuleInput{}, errStr("不支持的触发类型")
}
if req.CookieID == "" || !s.cookieOwnedByUser(r.Context(), userID, req.CookieID) {
return db.AutomationRuleInput{}, errStr("账号不存在或不属于当前用户")
}
if req.ItemID != "" && !s.itemOwnedByUser(r, userID, req.CookieID, req.ItemID) {
return db.AutomationRuleInput{}, errStr("商品不属于当前用户")
}
if req.Priority <= 0 {
req.Priority = 100
}
// config 保存配置,供当前处理流程使用
config := req.ConfigJSON
if config == "" {
config = "{}"
}
if !isJSONObject(config) {
return db.AutomationRuleInput{}, errStr("规则配置必须是 JSON 对象")
}
if len(req.Actions) == 0 {
return db.AutomationRuleInput{}, errStr("至少需要一个自动化动作")
}
if req.Name == "" {
req.Name = defaultAutomationRuleName(req.TriggerType, req.ItemID)
}
// actions 保存动作列表,供当前处理流程使用
actions := make([]db.AutomationActionInput, 0, len(req.Actions))
// hasSendCard、hasSendText、hasConfirmShipment 保存hasSendCard、hasSendText、hasConfirmShipment,供当前处理流程使用
hasSendCard, hasSendText, hasConfirmShipment := false, false, false
// i、act 表示当前遍历过程中的i、act
for i, act := range req.Actions {
// enabled 保存启用状态,供当前处理流程使用
enabled := true
if act.Enabled != nil {
enabled = *act.Enabled
}
act.ActionType = strings.TrimSpace(act.ActionType)
switch act.ActionType {
case automation.ActionConfirmShipment:
hasConfirmShipment = hasConfirmShipment || enabled
case automation.ActionSendCard:
if act.CardID <= 0 {
return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组")
}
// card、cardErr 保存card、cardErr,供当前处理流程使用
card, cardErr := s.Store.Cards.Get(r.Context(), act.CardID)
if cardErr != nil || card.UserID != userID {
return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户")
}
if card.Type == "api" {
return db.AutomationRuleInput{}, errStr("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密")
}
hasSendCard = hasSendCard || enabled
case automation.ActionSendText:
if strings.TrimSpace(act.MessageTemplate) == "" {
return db.AutomationRuleInput{}, errStr("发送文本动作必须填写文案")
}
hasSendText = hasSendText || enabled
default:
return db.AutomationRuleInput{}, errStr("不支持的动作类型")
}
if act.DeliveryCount <= 0 {
act.DeliveryCount = 1
}
if act.DelaySeconds < 0 || act.DelaySeconds > 3600 {
return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 3600 秒之间")
}
if act.ConfigJSON == "" {
act.ConfigJSON = "{}"
}
if !isJSONObject(act.ConfigJSON) {
return db.AutomationRuleInput{}, errStr("动作配置必须是 JSON 对象")
}
actions = append(actions, db.AutomationActionInput{
ActionType: act.ActionType, CardID: act.CardID, DeliveryCount: act.DeliveryCount,
MessageTemplate: act.MessageTemplate, DelaySeconds: act.DelaySeconds, ConfigJSON: act.ConfigJSON,
Enabled: enabled, SortOrder: firstNonZero(act.SortOrder, i+1),
})
}
switch req.TriggerType {
case automation.TriggerOrderPaid:
if !hasSendCard {
return db.AutomationRuleInput{}, errStr("付款后自动发货至少需要一个已启用的发送卡密动作")
}
case automation.TriggerBuyerReviewed:
if hasConfirmShipment {
return db.AutomationRuleInput{}, errStr("评价后规则不能包含确认发货动作")
}
if !hasSendCard && !hasSendText {
return db.AutomationRuleInput{}, errStr("评价后规则至少需要一个已启用的发送动作")
}
case automation.TriggerReviewMissingTimeout:
if hasConfirmShipment || hasSendCard {
return db.AutomationRuleInput{}, errStr("求评价规则只能发送文本")
}
if !hasSendText {
return db.AutomationRuleInput{}, errStr("求评价规则至少需要一个已启用的文本动作")
}
}
return db.AutomationRuleInput{
UserID: userID, CookieID: req.CookieID, ItemID: req.ItemID, Name: req.Name,
TriggerType: req.TriggerType, Enabled: req.Enabled, Priority: req.Priority,
ConfigJSON: config, Actions: actions,
}, nil
}
// defaultAutomationRuleName 负责default自动化规则名称相关处理。
func defaultAutomationRuleName(triggerType, itemID string) string {
// name 保存名称,供当前处理流程使用
name := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
}[triggerType]
if name == "" {
name = "自动化规则"
}
if strings.TrimSpace(itemID) != "" {
return name + " - " + strings.TrimSpace(itemID)
}
return name
}
// isJSONObject 负责isJSONObject相关处理。
func isJSONObject(s string) bool {
// m 保存m,供当前处理流程使用
var m map[string]any
return json.Unmarshal([]byte(s), &m) == nil
}
// firstNonZero 负责firstNonZero相关处理。
func firstNonZero(v, fallback int) int {
if v != 0 {
return v
}
return fallback
}
@@ -0,0 +1,49 @@
package server
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestAutomationIssuePortHTTPErrorBranches 验证 issue 应用 Port 接入后的 SQLite HTTP 错误分支。
func TestAutomationIssuePortHTTPErrorBranches(t *testing.T) {
// srv、cleanup 保存真实 SQLite 测试服务及清理函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 保存挂载认证和自动化 issue 路由的 HTTP 处理器。
handler := srv.Router()
// sessionCookie 保存测试管理员的认证会话。
sessionCookie := loginHelper(t, handler)
// invalidResolutionRequest 保存不支持处理动作的请求。
invalidResolutionRequest := httptest.NewRequest(http.MethodPost, "/automation-pending-tasks/1/resolve", strings.NewReader(`{"resolution":"continue"}`))
invalidResolutionRequest.AddCookie(sessionCookie)
// invalidResolutionResponse 捕获非法处理动作的响应。
invalidResolutionResponse := httptest.NewRecorder()
handler.ServeHTTP(invalidResolutionResponse, invalidResolutionRequest)
if invalidResolutionResponse.Code != http.StatusBadRequest || !strings.Contains(invalidResolutionResponse.Body.String(), "retry") {
t.Fatalf("非法延迟任务处理动作响应异常: status=%d body=%s", invalidResolutionResponse.Code, invalidResolutionResponse.Body.String())
}
// missingRunRequest 保存不存在自动化运行的处理请求。
missingRunRequest := httptest.NewRequest(http.MethodPost, "/automation-runs/999999/resolve", strings.NewReader(`{"resolution":"cancel"}`))
missingRunRequest.AddCookie(sessionCookie)
// missingRunResponse 捕获不存在运行的响应。
missingRunResponse := httptest.NewRecorder()
handler.ServeHTTP(missingRunResponse, missingRunRequest)
if missingRunResponse.Code != http.StatusNotFound {
t.Fatalf("不存在自动化运行响应异常: status=%d body=%s", missingRunResponse.Code, missingRunResponse.Body.String())
}
// listRequest 保存 SQLite issue 列表查询请求。
listRequest := httptest.NewRequest(http.MethodGet, "/automation-issues", nil)
listRequest.AddCookie(sessionCookie)
// listResponse 捕获 SQLite issue 列表响应。
listResponse := httptest.NewRecorder()
handler.ServeHTTP(listResponse, listRequest)
if listResponse.Code != http.StatusOK || !strings.Contains(listResponse.Body.String(), `"runs"`) || !strings.Contains(listResponse.Body.String(), `"pending_tasks"`) {
t.Fatalf("自动化 issue 列表响应异常: status=%d body=%s", listResponse.Code, listResponse.Body.String())
}
}
+295
View File
@@ -0,0 +1,295 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/auth"
)
// automationActionRequest 保存自动化动作请求,供当前处理流程使用
type automationActionRequest struct {
ActionType string `json:"action_type"`
CardID int64 `json:"card_id"`
DeliveryCount int `json:"delivery_count"`
MessageTemplate string `json:"message_template"`
DelaySeconds int `json:"delay_seconds"`
ConfigJSON string `json:"config_json"`
Enabled *bool `json:"enabled"`
SortOrder int `json:"sort_order"`
}
// automationRuleRequest 保存自动化规则请求,供当前处理流程使用
type automationRuleRequest struct {
CookieID string `json:"cookie_id"`
ItemID string `json:"item_id"`
Name string `json:"name"`
TriggerType string `json:"trigger_type"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
ConfigJSON string `json:"config_json"`
Actions []automationActionRequest `json:"actions"`
}
// listAutomationRules 负责list自动化规则列表相关处理。
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// query 保存查询,供当前处理流程使用
query := r.URL.Query()
// paginated 保存paginated,供当前处理流程使用
_, paginated := query["page"]
if !paginated {
// rules、err 保存rules、err,供当前处理流程使用
rules, err := s.automationRulesApplication().ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
writeJSON(w, http.StatusOK, automationRulesJSON(rules))
return
}
// page 保存页码,供当前处理流程使用
page := atoiDefault(query.Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
pageSize := atoiDefault(query.Get("page_size"), 10)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 10
}
if pageSize > 100 {
pageSize = 100
}
// cookieID 保存登录凭证ID,供当前处理流程使用
cookieID := strings.TrimSpace(query.Get("cookie_id"))
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
}
// triggerType 保存trigger类型,供当前处理流程使用
triggerType := strings.TrimSpace(query.Get("trigger_type"))
if triggerType != "" {
switch triggerType {
case automationapp.TriggerOrderPaid, automationapp.TriggerBuyerReviewed, automationapp.TriggerReviewMissingTimeout:
default:
writeErr(w, http.StatusBadRequest, "不支持的触发类型")
return
}
}
// enabled 保存启用状态,供当前处理流程使用
var enabled *bool
if // rawEnabled 保存原始启用状态,供当前处理流程使用
rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
// value、parseErr 保存value、parseErr,供当前处理流程使用
value, parseErr := strconv.ParseBool(rawEnabled)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
return
}
enabled = &value
}
// rules、total、err 保存rules、total、err,供当前处理流程使用
rules, total, err := s.automationRulesApplication().ListPageForUser(r.Context(), automationapp.RuleFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
// filter 保存filter,供当前处理流程使用
filter := automationapp.RuleFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"),
}
// triggerCounts、err 保存triggerCounts、err,供当前处理流程使用
triggerCounts, err := s.automationRulesApplication().CountByTriggerForUser(r.Context(), filter)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计自动化规则失败")
return
}
// totalPages 保存总数Pages,供当前处理流程使用
totalPages := (total + pageSize - 1) / pageSize
if totalPages > 0 && page > totalPages {
page = totalPages
rules, _, err = s.automationRulesApplication().ListPageForUser(r.Context(), automationapp.RuleFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
}
writeJSON(w, http.StatusOK, automationRulePageResponse{
Success: true, Data: automationRulesJSON(rules), Total: total, Page: page,
PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts,
})
}
// automationRulesJSON 负责自动化规则列表JSON相关处理。
func automationRulesJSON(rules []automationapp.Rule) []automationRuleResponse {
// out 保存out,供当前处理流程使用
out := make([]automationRuleResponse, 0, len(rules))
// rule 表示当前遍历过程中的规则
for _, rule := range rules {
// actions 保存动作列表,供当前处理流程使用
actions := make([]automationActionResponse, 0, len(rule.Actions))
// action 表示当前遍历过程中的动作
for _, action := range rule.Actions {
actions = append(actions, automationActionResponse{
ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName,
DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate,
DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled,
SortOrder: action.SortOrder,
})
}
out = append(out, automationRuleResponse{
ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle,
Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority,
ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt,
})
}
return out
}
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.automationRulesApplication().Create(r.Context(), in)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
return
}
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateAutomationRule 负责update自动化规则相关处理。
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if // err 保存err,供当前处理流程使用
err := s.automationRulesApplication().Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if errors.Is(err, automationapp.ErrRuleNotFound) {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
writeErr(w, http.StatusInternalServerError, "更新自动化规则失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAutomationRule 负责delete自动化规则相关处理。
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.automationRulesApplication().Delete(r.Context(), sess.UserID, ruleID); err != nil {
if errors.Is(err, automationapp.ErrRuleNotFound) {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
if errors.Is(err, automationapp.ErrRuleActive) {
writeErr(w, http.StatusConflict, "规则仍有运行中或待人工处理的任务,处理完成后才能删除")
return
}
writeErr(w, http.StatusInternalServerError, "删除自动化规则失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// automationRuleDraft 将 HTTP 请求转换为应用层规则草稿。
func automationRuleDraft(req automationRuleRequest) automationapp.RuleDraft {
// actions 保存转换后的应用层动作草稿,不携带数据库模型。
actions := make([]automationapp.ActionDraft, 0, len(req.Actions))
// action 是当前待转换的 HTTP 动作请求。
for _, action := range req.Actions {
actions = append(actions, automationapp.ActionDraft{ActionType: action.ActionType, CardID: action.CardID,
DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, DelaySeconds: action.DelaySeconds,
ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, SortOrder: action.SortOrder})
}
return automationapp.RuleDraft{CookieID: req.CookieID, ItemID: req.ItemID, Name: req.Name, TriggerType: req.TriggerType,
Enabled: req.Enabled, Priority: req.Priority, ConfigJSON: req.ConfigJSON, Actions: actions}
}
// defaultAutomationRuleName 保留旧测试和兼容调用所需的默认名称函数。
func defaultAutomationRuleName(triggerType, itemID string) string {
// name 保存按触发类型选择的默认规则名称,必要时附加商品标识。
name := map[string]string{automationapp.TriggerOrderPaid: "付款后自动发货", automationapp.TriggerBuyerReviewed: "评价后发送赠品", automationapp.TriggerReviewMissingTimeout: "超时未评价求评价"}[triggerType]
if name == "" {
name = "自动化规则"
}
if strings.TrimSpace(itemID) != "" {
return name + " - " + strings.TrimSpace(itemID)
}
return name
}
// isJSONObject 保留规则配置测试需要的 JSON 对象判断。
func isJSONObject(raw string) bool {
// value 保存 JSON 对象解析结果,仅用于判断配置顶层类型。
var value map[string]any
return json.Unmarshal([]byte(raw), &value) == nil
}
// firstNonZero 保留旧兼容调用的非零回退行为。
func firstNonZero(value, fallback int) int {
if value != 0 {
return value
}
return fallback
}
@@ -0,0 +1,135 @@
package server
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
cardsapp "xianyu-go/internal/application/cards"
"xianyu-go/internal/db"
)
// TestCardApplicationEndpointsEnforceOwnership 验证详情、更新和删除均由应用服务执行用户隔离。
func TestCardApplicationEndpointsEnforceOwnership(t *testing.T) {
// server、store、cleanup 保存测试 HTTP 服务、SQLite 存储和资源释放函数。
server, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 是创建跨用户数据夹具时使用的非取消上下文。
ctx := context.Background()
// created、createUserErr 保存卡券所有者创建结果及数据库错误。
created, createUserErr := store.Users.Create(ctx, "card-owner", "[email protected]", "pw")
if createUserErr != nil || !created {
t.Fatalf("创建卡券所有者失败 created=%v err=%v", created, createUserErr)
}
// owner、ownerErr 保存新用户详情及查询错误。
owner, ownerErr := store.Users.GetByUsername(ctx, "card-owner")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// cardID、createCardErr 保存属于新用户的卡券标识及创建错误。
cardID, createCardErr := store.Cards.Create(ctx, &db.CardFull{Name: "他人卡券", Type: "text", TextContent: "SECRET", Enabled: true, UserID: owner.ID})
if createCardErr != nil {
t.Fatal(createCardErr)
}
// handler 是包含认证中间件和卡券路由的测试处理器。
handler := server.Router()
// adminCookie 是不拥有测试卡券的管理员会话 Cookie。
adminCookie := loginHelper(t, handler)
// testCase 是当前待验证的跨用户 HTTP 操作。
for _, testCase := range []struct {
// name 是测试子场景名称。
name string
// method 是请求使用的 HTTP 方法。
method string
// body 是更新操作使用的请求体;其他操作为空。
body string
}{
{name: "get", method: http.MethodGet},
{name: "update", method: http.MethodPut, body: `{"name":"篡改","type":"text","text_content":"X","enabled":true}`},
{name: "delete", method: http.MethodDelete},
} {
t.Run(testCase.name, func(t *testing.T) {
// request 是当前跨用户访问请求。
request := httptest.NewRequest(testCase.method, "/cards/"+strconv.FormatInt(cardID, 10), strings.NewReader(testCase.body))
request.AddCookie(adminCookie)
// response 记录当前请求的 HTTP 状态和统一错误响应。
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusForbidden {
t.Fatalf("跨用户操作应返回 403,status=%d body=%s", response.Code, response.Body.String())
}
})
}
// remaining、remainingErr 保存跨用户删除尝试后的数据库卡券记录及错误。
remaining, remainingErr := store.Cards.Get(ctx, cardID)
if remainingErr != nil || remaining.UserID != owner.ID || remaining.Name != "他人卡券" {
t.Fatalf("跨用户操作不得修改或删除卡券,card=%+v err=%v", remaining, remainingErr)
}
}
// TestCardApplicationEndpointsTreatNonPositiveIDAsMissing 验证数字格式合法但非正数的标识保持 404 兼容语义。
func TestCardApplicationEndpointsTreatNonPositiveIDAsMissing(t *testing.T) {
// server、cleanup 保存测试 HTTP 服务和资源释放函数。
server, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是包含认证中间件和卡券路由的测试处理器。
handler := server.Router()
// sessionCookie 是管理员登录后的认证 Cookie。
sessionCookie := loginHelper(t, handler)
// testCase 是当前待验证的卡券操作和请求体。
for _, testCase := range []struct {
// name 是测试子场景名称。
name string
// method 是请求使用的 HTTP 方法。
method string
// body 是更新操作使用的合法请求体。
body string
}{
{name: "get", method: http.MethodGet},
{name: "update", method: http.MethodPut, body: `{"name":"不存在","type":"text","text_content":"X","enabled":true}`},
{name: "delete", method: http.MethodDelete},
} {
t.Run(testCase.name, func(t *testing.T) {
// request 是使用零值卡券标识的认证请求。
request := httptest.NewRequest(testCase.method, "/cards/0", strings.NewReader(testCase.body))
request.AddCookie(sessionCookie)
// response 记录资源缺失兼容响应。
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusNotFound {
t.Fatalf("非正数卡券标识应返回 404,status=%d body=%s", response.Code, response.Body.String())
}
})
}
}
// TestWriteCardReadErrorClassification 验证读取错误分别映射为 404、403 和 500。
func TestWriteCardReadErrorClassification(t *testing.T) {
// testCase 是当前应用错误与期望 HTTP 状态的映射。
for _, testCase := range []struct {
// name 是错误分类子场景名称。
name string
// err 是应用服务返回给 HTTP 边界的错误。
err error
// wantStatus 是期望写入的 HTTP 状态码。
wantStatus int
}{
{name: "not-found", err: cardsapp.ErrNotFound, wantStatus: http.StatusNotFound},
{name: "invalid-numeric-id", err: cardsapp.ErrInvalidCardID, wantStatus: http.StatusNotFound},
{name: "forbidden", err: cardsapp.ErrForbidden, wantStatus: http.StatusForbidden},
{name: "infrastructure", err: errors.New("database unavailable"), wantStatus: http.StatusInternalServerError},
} {
t.Run(testCase.name, func(t *testing.T) {
// response 记录错误映射函数写入的状态和统一响应体。
response := httptest.NewRecorder()
writeCardReadError(response, testCase.err)
if response.Code != testCase.wantStatus {
t.Fatalf("错误状态不匹配 got=%d want=%d body=%s", response.Code, testCase.wantStatus, response.Body.String())
}
})
}
}
+37 -42
View File
@@ -1,6 +1,7 @@
package server
import (
"errors"
"fmt"
"net/http"
"strconv"
@@ -8,8 +9,8 @@ import (
"github.com/go-chi/chi/v5"
cardsapp "xianyu-go/internal/application/cards"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// maxCardBatchRows 保存max卡密批次Rows,供当前处理流程使用
@@ -31,8 +32,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
// 表格最大 5 MiB(卡密组定义都很小)。
r.Body = http.MaxBytesReader(w, r.Body, maxCardBatchUploadBytes)
if // err 保存err,供当前处理流程使用
err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil {
// err 表示解析 multipart 表单时遇到的格式或大小限制错误。
if err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil {
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
return
}
@@ -114,8 +115,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
continue
}
// cf 保存cf,供当前处理流程使用
cf := &db.CardFull{
// draft 保存当前表格行转换出的应用卡券草稿。
draft := cardsapp.Draft{
Name: name,
Type: cardType,
Description: firstImportString(m, "description", "描述"),
@@ -124,23 +125,22 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
IsMultiSpec: parseLooseBool(firstImportString(m, "is_multi_spec", "多规格")),
SpecName: firstImportString(m, "spec_name", "规格名"),
SpecValue: firstImportString(m, "spec_value", "规格值"),
UserID: sess.UserID,
}
if // v 保存v,供当前处理流程使用
v := firstImportString(m, "enabled", "启用"); v != "" {
cf.Enabled = parseLooseBool(v)
// v 保存表格行提供的可选启用状态文本。
if v := firstImportString(m, "enabled", "启用"); v != "" {
draft.Enabled = parseLooseBool(v)
}
switch cardType {
case "text":
cf.TextContent = content
draft.TextContent = content
case "data":
cf.DataContent = content
draft.DataContent = content
case "image":
cf.ImageURL = content
draft.ImageURL = content
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Cards.Create(r.Context(), cf)
// id、err 保存应用服务创建的卡券标识及逐行错误。
id, err := s.cardsApplication().Create(r.Context(), sess.UserID, draft)
if err != nil {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "创建失败: " + err.Error()})
failed++
@@ -161,47 +161,42 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
// appendCardData 往 data 类型卡密组追加卡密号(按行)。
func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存认证中间件注入的当前用户会话。
sess := auth.SessionFromContext(r.Context())
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
// id、parseErr 保存路径中的卡券标识及数字解析错误。
id, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Content string `json:"content"`
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
// req 保存具名 DTO 解码后的追加库存请求。
var req cardAppendRequest
// decodeErr 表示追加请求 JSON 的解码错误。
if decodeErr := decodeJSON(r, &req); decodeErr != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// content 保存内容,供当前处理流程使用
// content 保存去除首尾空白后的待追加卡密内容。
content := strings.TrimSpace(req.Content)
if content == "" {
writeErr(w, http.StatusBadRequest, "内容为空")
return
}
// cf、err 保存cf、err,供当前处理流程使用
cf, err := s.Store.Cards.Get(r.Context(), id)
// added、err 保存应用服务追加的库存行数及业务或持久化错误。
added, err := s.cardsApplication().AppendData(r.Context(), sess.UserID, id, content)
if err != nil {
writeErr(w, http.StatusNotFound, "卡券不存在")
return
}
if cf.UserID != sess.UserID {
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
return
}
if cf.Type != "data" {
writeErr(w, http.StatusBadRequest, "只有 data(批量卡密)类型支持追加卡密")
return
}
// added、err 保存added、err,供当前处理流程使用
added, err := s.Store.Cards.AppendBatchData(r.Context(), id, content)
if err != nil {
writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error())
// validationErr 用于识别可以直接返回客户端的稳定校验提示。
var validationErr *cardsapp.ValidationError
switch {
case errors.Is(err, cardsapp.ErrNotFound):
writeErr(w, http.StatusNotFound, "卡券不存在")
case errors.Is(err, cardsapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
case errors.Is(err, cardsapp.ErrNotDataType), errors.As(err, &validationErr):
writeErr(w, http.StatusBadRequest, err.Error())
default:
writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error())
}
return
}
writeJSON(w, http.StatusOK, cardAppendResponse{Success: true, Added: added})
+141 -142
View File
@@ -1,17 +1,51 @@
package server
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
cardsapp "xianyu-go/internal/application/cards"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountCardsReal 卡券 CRUD(真实实现)。发货规则已统一到 automation_rules。
// cardMutationRequest 是卡券创建与更新接口共用的具名请求 DTO。
type cardMutationRequest struct {
// Name 是用户可见的卡券组名称。
Name string `json:"name"`
// Type 是 text、data、image 或历史兼容的 api 类型。
Type string `json:"type"`
// APIConfig 是历史 API 卡券配置文本。
APIConfig string `json:"api_config"`
// TextContent 是 text 类型自动发货时发送的文本内容。
TextContent string `json:"text_content"`
// DataContent 是 data 类型尚未消费的逐行卡密库存。
DataContent string `json:"data_content"`
// ImageURL 是 image 类型自动发货时发送的图片地址。
ImageURL string `json:"image_url"`
// Description 是用户维护的卡券组说明。
Description string `json:"description"`
// Enabled 表示保存后是否允许自动化规则使用该卡券组。
Enabled bool `json:"enabled"`
// DelaySeconds 是自动发货前的延迟秒数。
DelaySeconds int `json:"delay_seconds"`
// IsMultiSpec 表示卡券组是否只匹配指定商品规格。
IsMultiSpec bool `json:"is_multi_spec"`
// SpecName 是多规格匹配使用的规格名称。
SpecName string `json:"spec_name"`
// SpecValue 是多规格匹配使用的规格值。
SpecValue string `json:"spec_value"`
}
// cardAppendRequest 是 data 类型卡券追加库存接口的具名请求 DTO。
type cardAppendRequest struct {
// Content 是待追加的逐行卡密文本,空行由数据库层按既有规则处理。
Content string `json:"content"`
}
// mountCardsReal 挂载卡券 CRUD、批量创建和库存追加路由;发货规则由 automation_rules 负责。
func (s *Server) mountCardsReal(r chi.Router) {
r.Get("/cards", s.listCards)
r.Post("/cards", s.createCard)
@@ -23,12 +57,12 @@ func (s *Server) mountCardsReal(r chi.Router) {
r.Delete("/cards/{card_id}", s.deleteCard)
}
// listCards 负责list卡密列表相关处理。
// listCards 将认证用户交给应用服务,并把卡券应用模型转换为 HTTP DTO。
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// cards、err 保存cards、err,供当前处理流程使用
cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID)
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
// cards、err 保存应用服务返回的用户卡券列表及查询错误。
cards, err := s.cardsApplication().List(r.Context(), session.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -36,176 +70,141 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newCardResponses(cards))
}
// getCard 负责get卡密相关处理。
// getCard 解析路径标识并由应用服务统一校验资源存在性和用户归属。
func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
// cardID、parseErr 保存路径中的卡券标识及数字解析错误。
cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// cf、ok 保存cf、ok,供当前处理流程使用
cf, ok := s.requireCardOwner(w, r, id)
if !ok {
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
// card、err 保存应用服务返回的卡券组及所有权或查询错误。
card, err := s.cardsApplication().Get(r.Context(), session.UserID, cardID)
if err != nil {
writeCardReadError(w, err)
return
}
writeJSON(w, http.StatusOK, newCardResponse(*cf))
writeJSON(w, http.StatusOK, newCardResponse(card))
}
// createCard 负责create卡密相关处理。
// createCard 解码 HTTP 请求,并由应用服务完成输入校验、类型限制和所有者写入。
func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// cf、err 保存cf、err,供当前处理流程使用
cf, err := decodeCard(r)
// draft、decodeErr 保存请求转换后的应用输入及 JSON 解码错误。
draft, decodeErr := decodeCardDraft(r)
if decodeErr != nil {
writeErr(w, http.StatusBadRequest, decodeErr.Error())
return
}
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
// cardID、err 保存创建后的卡券标识及业务或持久化错误。
cardID, err := s.cardsApplication().Create(r.Context(), session.UserID, draft)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
// validationError 用于识别可直接返回客户端的稳定业务校验提示。
var validationError *cardsapp.ValidationError
switch {
case errors.As(err, &validationError):
writeErr(w, http.StatusBadRequest, validationError.Error())
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
default:
writeErr(w, http.StatusInternalServerError, "创建失败")
}
return
}
cf.UserID = sess.UserID
if cf.Type == "api" {
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Cards.Create(r.Context(), cf)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建失败")
return
}
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: cardID})
}
// updateCard 负责update卡密相关处理。
// updateCard 解码路径和请求体,并由应用服务完成输入校验、归属校验及更新。
func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
// cardID、parseErr 保存路径中的卡券标识及数字解析错误。
cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
// cf、err 保存cf、err,供当前处理流程使用
cf, err := decodeCard(r)
// draft、decodeErr 保存请求转换后的应用输入及 JSON 解码错误。
draft, decodeErr := decodeCardDraft(r)
if decodeErr != nil {
writeErr(w, http.StatusBadRequest, decodeErr.Error())
return
}
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
// err 是应用服务返回的业务校验、所有权或持久化错误。
err := s.cardsApplication().Update(r.Context(), session.UserID, cardID, draft)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// existing、ok 保存existing、ok,供当前处理流程使用
existing, ok := s.requireCardOwner(w, r, id)
if !ok {
return
}
if cf.Type == "api" && existing.Type != "api" {
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型")
return
}
cf.ID = id
cf.UserID = existing.UserID
if // err 保存err,供当前处理流程使用
err := s.Store.Cards.Update(r.Context(), cf); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
// validationError 用于识别可直接返回客户端的稳定业务校验提示。
var validationError *cardsapp.ValidationError
switch {
case errors.As(err, &validationError):
writeErr(w, http.StatusBadRequest, validationError.Error())
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型")
case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID):
writeErr(w, http.StatusNotFound, "卡券不存在")
case errors.Is(err, cardsapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
default:
writeErr(w, http.StatusInternalServerError, "更新失败")
}
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteCard 负责delete卡密相关处理。
// deleteCard 解析路径标识,并由应用服务在归属校验后删除卡券组。
func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
// cardID、parseErr 保存路径中的卡券标识及数字解析错误。
cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
if // ok 保存ok,供当前处理流程使用
_, ok := s.requireCardOwner(w, r, id); !ok {
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cards.Delete(r.Context(), id); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
// err 是应用服务返回的资源、所有权或删除持久化错误。
err := s.cardsApplication().Delete(r.Context(), session.UserID, cardID)
if err != nil {
switch {
case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID):
writeErr(w, http.StatusNotFound, "卡券不存在")
case errors.Is(err, cardsapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
default:
writeErr(w, http.StatusInternalServerError, "删除失败")
}
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// decodeCard 负责decode卡密相关处理。
func decodeCard(r *http.Request) (*db.CardFull, error) {
// req 保存req,供当前处理流程使用
var req struct {
Name string `json:"name"`
Type string `json:"type"`
APIConfig string `json:"api_config"`
TextContent string `json:"text_content"`
DataContent string `json:"data_content"`
ImageURL string `json:"image_url"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
DelaySeconds int `json:"delay_seconds"`
IsMultiSpec bool `json:"is_multi_spec"`
SpecName string `json:"spec_name"`
SpecValue string `json:"spec_value"`
// decodeCardDraft 把具名 HTTP 请求 DTO 转换为应用输入;业务校验由应用服务统一负责。
func decodeCardDraft(r *http.Request) (cardsapp.Draft, error) {
// request 是当前待解码的卡券创建或更新请求。
var request cardMutationRequest
// err 表示请求 JSON 无法解码为卡券输入 DTO 的格式错误。
if err := decodeJSON(r, &request); err != nil {
return cardsapp.Draft{}, err
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
return nil, err
}
if req.Name == "" || req.Type == "" {
return nil, errStr("名称和类型不能为空")
}
switch req.Type {
case "text", "data", "image", "api":
default:
return nil, errStr("类型必须为 text、data、image 或 api")
}
if req.DelaySeconds < 0 || req.DelaySeconds > 3600 {
return nil, errStr("延时发货必须在 0 到 3600 秒之间")
}
switch req.Type {
case "text":
if strings.TrimSpace(req.TextContent) == "" {
return nil, errStr("文本卡密内容不能为空")
}
case "data":
if strings.TrimSpace(req.DataContent) == "" {
return nil, errStr("数据卡密内容不能为空")
}
case "image":
if strings.TrimSpace(req.ImageURL) == "" {
return nil, errStr("图片卡密 URL 不能为空")
}
}
return &db.CardFull{
Name: req.Name, Type: req.Type, APIConfig: req.APIConfig, TextContent: req.TextContent,
DataContent: req.DataContent, ImageURL: req.ImageURL, Description: req.Description,
Enabled: req.Enabled, DelaySeconds: req.DelaySeconds, IsMultiSpec: req.IsMultiSpec,
SpecName: req.SpecName, SpecValue: req.SpecValue,
return cardsapp.Draft{
Name: request.Name, Type: request.Type, APIConfig: request.APIConfig,
TextContent: request.TextContent, DataContent: request.DataContent, ImageURL: request.ImageURL,
Description: request.Description, Enabled: request.Enabled, DelaySeconds: request.DelaySeconds,
IsMultiSpec: request.IsMultiSpec, SpecName: request.SpecName, SpecValue: request.SpecValue,
}, nil
}
// itemOwnedByUser 校验 cookieID 归属当前用户且其下存在 itemID 商品。
// 由自动化规则校验复用(原 deliveryRuleItemOwned,发货规则删除后改名)。
// itemOwnedByUser 负责商品OwnedBy用户相关处理。
func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID string) bool {
if itemID == "" {
return true
// writeCardReadError 将详情查询的应用错误映射为既有 HTTP 状态和统一错误响应。
func writeCardReadError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID):
writeErr(w, http.StatusNotFound, "卡券不存在")
case errors.Is(err, cardsapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
default:
writeErr(w, http.StatusInternalServerError, "查询失败")
}
if cookieID == "" {
return false
}
owned, err := s.Store.Cookies.ExistsOwned(r.Context(), userID, cookieID) // owned 和 err 表示账号归属及查询错误。
if err != nil || !owned {
return false
}
_, err = s.Store.Items.Get(r.Context(), cookieID, itemID)
return err == nil
}
// errStr 负责errStr相关处理。
func errStr(s string) error { return &simpleError{s} }
// simpleError 保存simple错误,供当前处理流程使用
type simpleError struct{ msg string }
// Error 负责错误相关处理。
func (e *simpleError) Error() string { return e.msg }
+14
View File
@@ -0,0 +1,14 @@
package server
import (
"xianyu-go/internal/adapter"
chatapp "xianyu-go/internal/application/chat"
)
// newChatSendingApplication 创建实时聊天应用服务,Server 仅负责注入运行时依赖。
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)
}
+47 -201
View File
@@ -14,10 +14,9 @@ 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"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// mountChat 负责mount聊天相关处理。
@@ -30,74 +29,6 @@ func (s *Server) mountChat(r chi.Router) {
r.Get("/api/chat/ws", s.chatWebSocket)
}
// storeChatApplicationRepository 将数据库聊天查询适配为应用层聊天端口。
type storeChatApplicationRepository struct {
// store 保存数据库聚合入口,仅在适配器内执行窄聊天查询。
store *db.Store
}
// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。
func (r storeChatApplicationRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) {
// rows 保存数据库返回的消息记录。
rows, err := r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit)
if err != nil {
return nil, err
}
// messages 保存脱离数据库模型的应用层消息。
messages := make([]chatapp.Message, 0, len(rows))
// row 表示当前待转换的数据库聊天消息。
for _, row := range rows {
messages = append(messages, chatapp.Message{
ID: row.ID, AccountID: row.CookieID, ChatID: row.ChatID, MessageKey: row.MessageKey,
Direction: row.Direction, SenderID: row.SenderID, SenderName: row.SenderName,
MessageType: row.MessageType, Content: row.Content, Status: row.Status, SentAt: row.SentAt,
})
}
return messages, nil
}
// ListSessions 查询带用户归属条件的聊天会话,并转换为应用层模型。
func (r storeChatApplicationRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) {
// rows 保存数据库返回的会话记录。
rows, err := r.store.Chats.ListSessions(ctx, userID, accountID, limit)
if err != nil {
return nil, err
}
// sessions 保存脱离数据库模型的应用层会话摘要。
sessions := make([]chatapp.Session, 0, len(rows))
// row 表示当前待转换的数据库聊天会话。
for _, row := range rows {
sessions = append(sessions, chatapp.Session{
AccountID: row.CookieID, ChatID: row.ChatID, BuyerID: row.BuyerID,
BuyerName: row.BuyerName, BuyerAvatar: row.BuyerAvatar, ItemID: row.ItemID,
ItemTitle: row.ItemTitle, LastMessage: row.LastMessage, LastMessageAt: row.LastMessageAt,
UnreadCount: row.UnreadCount,
})
}
return sessions, nil
}
// newStoreChatApplicationRepository 创建聊天历史应用服务使用的数据库适配器。
func newStoreChatApplicationRepository(store *db.Store) chatapp.Repository {
if store == nil || store.Chats == nil {
return nil
}
return storeChatApplicationRepository{store: store}
}
// dbChatSessionFromApplication 将非敏感应用会话转换为平台身份适配器可消费的数据库形状。
func dbChatSessionFromApplication(session chatapp.Session) db.ChatSession {
return db.ChatSession{
CookieID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID,
BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID,
ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt,
UnreadCount: session.UnreadCount,
}
}
// 确保数据库适配器覆盖聊天历史应用端口的全部能力。
var _ chatapp.Repository = storeChatApplicationRepository{}
// chatApplication 返回当前 Server 绑定的聊天历史应用服务。
func (s *Server) chatApplication() *chatapp.Service {
return s.applicationServiceSet().chat
@@ -121,8 +52,8 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
var hasMore bool
// nextCursor 保存next游标,供当前处理流程使用
var nextCursor int64
if // err 保存err,供当前处理流程使用
err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil {
if // err 保存清理空会话的错误。
err := s.chatApplication().CleanupEmptySessions(r.Context(), accountID); err != nil {
writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败")
return
}
@@ -152,88 +83,24 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
}
}
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200))
// rows、err 保存应用层会话摘要及查询错误。
rows, err := s.chatApplication().ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200))
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取聊天会话失败")
return
}
if refresh {
if // cookieValue、cookieErr 保存登录凭证Value、cookieErr,供当前处理流程使用
cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil {
// client、canResolve 保存client、canResolve,供当前处理流程使用
client, canResolve := s.mtopClient().(interface {
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
})
if !canResolve {
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
return
}
// resolveCtx、resolveCancel 保存resolveCtx、resolve取消,供当前处理流程使用
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
defer resolveCancel()
// jobs 保存jobs,供当前处理流程使用
jobs := make(chan int)
// workers 保存workers,供当前处理流程使用
var workers sync.WaitGroup
// sessionOnce 保存会话Once,供当前处理流程使用
var sessionOnce sync.Once
// sessionErr 保存会话Err,供当前处理流程使用
var sessionErr error
for // worker 保存工作器,供当前处理流程使用
worker := 0; worker < 8; worker++ {
workers.Add(1)
go func() {
defer workers.Done()
// index 表示当前遍历过程中的index
for index := range jobs {
// infoCtx、cancel 保存infoCtx、cancel,供当前处理流程使用
infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second)
// info、infoErr 保存info、infoErr,供当前处理流程使用
info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID)
cancel()
if mtop.IsSessionExpiredErr(infoErr) {
sessionOnce.Do(func() {
sessionErr = infoErr
resolveCancel()
})
continue
}
if infoErr != nil || info == nil {
continue
}
if // nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(info.Nickname); nickname != "" {
rows[index].BuyerName = nickname
}
if info.AvatarURL != "" {
rows[index].BuyerAvatar = info.AvatarURL
}
_ = s.Store.Chats.UpdateSessionIdentity(resolveCtx, accountID, rows[index].ChatID,
rows[index].BuyerID, rows[index].BuyerName, rows[index].BuyerAvatar)
}
}()
}
queue:
// index 表示当前遍历过程中的index
for index := range rows {
if rows[index].BuyerID == "1400" {
continue
}
select {
case jobs <- index:
case <-resolveCtx.Done():
break queue
}
}
close(jobs)
workers.Wait()
if sessionErr != nil {
s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr)
}
// resolveCtx 和 resolveCancel 限制联系人身份补全的总时长。
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
// refreshedRows 和 sessionErr 保存应用层身份补全结果及首个平台错误。
refreshedRows, sessionErr := s.chatApplication().RefreshSessionIdentities(resolveCtx, accountID, rows)
resolveCancel()
rows = refreshedRows
if sessionErr != nil {
s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr)
}
}
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOsFromApplication(rows), HasMore: hasMore, NextCursor: nextCursor})
}
// sendChatImage 负责send聊天图片相关处理。
@@ -340,24 +207,19 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
cancel()
if fetchErr == nil {
// sessions 保存sessions,供当前处理流程使用
sessions, _ := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500)
// current 保存current,供当前处理流程使用
var current db.ChatSession
// candidate 表示当前遍历过程中的candidate
for _, candidate := range sessions {
if candidate.ChatID == chatID {
current = candidate
break
}
}
current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID)
// page、saveErr 保存page、saveErr,供当前处理流程使用
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, current, body)
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, adapter.ChatSessionFromApplication(current), body)
if saveErr != nil {
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
return
}
current = s.resolveSelectedChatIdentity(r.Context(), accountID, current)
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, NextCursor: page.NextCursor, Session: newChatSessionDTO(current)})
// 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
}
}
@@ -370,43 +232,16 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
return
}
// session 是应用层返回的非敏感会话摘要,供平台身份适配器补齐展示名称。
session := dbChatSessionFromApplication(page.Session)
session := page.Session
if session.ChatID != "" {
session = s.resolveSelectedChatIdentity(r.Context(), accountID, session)
}
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(session)})
}
// resolveSelectedChatIdentity 负责resolveSelected聊天Identity相关处理。
func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession {
if session.BuyerID != "1400" {
// cookies、cookieErr 保存cookies、cookieErr,供当前处理流程使用
cookies, cookieErr := s.Store.Cookies.GetValue(ctx, accountID)
// client、supported 保存client、supported,供当前处理流程使用
client, supported := s.mtopClient().(interface {
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
})
if cookieErr == nil && supported {
// resolveCtx、cancel 保存resolveCtx、cancel,供当前处理流程使用
resolveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
// info、err 保存info、err,供当前处理流程使用
info, err := client.FetchChatUserInfo(resolveCtx, cookies, session.ChatID)
cancel()
if err == nil && info != nil {
if // nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(info.Nickname); nickname != "" {
session.BuyerName = nickname
}
if info.AvatarURL != "" {
session.BuyerAvatar = info.AvatarURL
}
} else if err != nil {
s.recoverExpiredMTOPSession(ctx, accountID, err)
}
// resolved 和 identityErr 保存身份补全后的会话及平台查询错误。
resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), session)
if identityErr != nil {
s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr)
}
session = resolved
}
_ = s.Store.Chats.UpdateSessionIdentity(ctx, accountID, session.ChatID, session.BuyerID, session.BuyerName, session.BuyerAvatar)
return session
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTOFromApplication(session)})
}
// sendChatMessageRequest 保存send聊天消息请求,供当前处理流程使用
@@ -481,10 +316,10 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().MarkChatRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
if // err 保存应用层已读状态更新错误。
err := s.chatApplication().MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
return
}
@@ -505,18 +340,20 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
return
}
defer unsubscribe()
// conn、err 保存conn、err,供当前处理流程使用
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
if err != nil {
unsubscribe()
return
}
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
conn.SetReadLimit(8 << 10)
// readerWG 等待读取 goroutine 在连接关闭后退出,避免请求返回时遗留后台任务。
var readerWG sync.WaitGroup
readerWG.Add(1)
go func() {
defer readerWG.Done()
for {
if // readErr 保存readErr,供当前处理流程使用
_, _, readErr := conn.Read(ctx); readErr != nil {
@@ -525,6 +362,14 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
}
}
}()
// cleanup 统一负责取消请求、关闭 WebSocket、等待读取任务和释放聊天订阅。
cleanup := func() {
cancel()
_ = conn.Close(websocket.StatusNormalClosure, "")
readerWG.Wait()
unsubscribe()
}
defer cleanup()
if // err 保存err,供当前处理流程使用
err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
return
@@ -549,7 +394,8 @@ func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
}
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
owned, err := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, accountID) // owned 和 err 表示账号归属及查询错误。
// owned 和 err 表示聊天应用端口返回的账号归属及查询错误。
owned, err := s.chatApplication().OwnsAccount(r.Context(), sess.UserID, accountID)
return err == nil && owned
}
-154
View File
@@ -1,154 +0,0 @@
package server
import (
"context"
"xianyu-go/internal/db"
)
// communicationRepository 定义通信应用服务隔离账号任务、通知绑定和聊天历史所需的最小持久化能力。
type communicationRepository interface {
// GetAccountTaskSettings 读取账号任务设置。
GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error)
// UpsertAccountTaskSettings 保存账号任务设置。
UpsertAccountTaskSettings(ctx context.Context, settings db.AccountTaskSettings) error
// ListAccountTaskRuns 查询账号任务运行记录。
ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error)
// ListNotificationChannels 查询用户拥有的通知渠道。
ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error)
// CreateNotificationChannel 创建通知渠道。
CreateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow) (int64, error)
// UpdateNotificationChannel 更新用户拥有的通知渠道。
UpdateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow, userID int64) error
// GetNotificationChannel 查询用户拥有的单个通知渠道。
GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error)
// DeleteNotificationChannel 删除用户拥有的通知渠道。
DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error
// GetNotificationChannelConfig 查询通知渠道发送配置。
GetNotificationChannelConfig(ctx context.Context, channelID int64) (*db.NotificationChannel, error)
// ListNotificationBindings 查询用户账号通知绑定。
ListNotificationBindings(ctx context.Context, userID int64) ([]db.NotificationBindingRow, error)
// SetNotificationBindings 覆盖保存账号通知绑定。
SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error
// GetNotificationBindingIDs 查询账号当前启用的通知渠道。
GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error)
// SetSingleNotificationBinding 更新单个通知绑定状态。
SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error
// DeleteNotificationBinding 删除用户账号的一条通知绑定。
DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error
// DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。
DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error
// GetCookieValue 读取账号 Cookie 明文。
GetCookieValue(ctx context.Context, cookieID string) (string, error)
// UpdateCookieValue 更新已存在账号的 Cookie 明文。
UpdateCookieValue(ctx context.Context, cookieID, value string) error
// MarkChatRead 将聊天会话标记为已读。
MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error
}
// storeCommunicationRepository 将完整 Store 适配为通信应用服务窄 repository。
type storeCommunicationRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// GetAccountTaskSettings 委托账号任务设置查询。
func (r storeCommunicationRepository) GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) {
return r.store.AccountTasks.Get(ctx, cookieID)
}
// UpsertAccountTaskSettings 委托账号任务设置写入。
func (r storeCommunicationRepository) UpsertAccountTaskSettings(ctx context.Context, settings db.AccountTaskSettings) error {
return r.store.AccountTasks.Upsert(ctx, settings)
}
// ListAccountTaskRuns 委托账号任务运行记录查询。
func (r storeCommunicationRepository) ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) {
return r.store.AccountTasks.RecentRuns(ctx, cookieID, limit)
}
// ListNotificationChannels 委托用户通知渠道查询。
func (r storeCommunicationRepository) ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) {
return r.store.Notifications.AllChannelsForUser(ctx, userID)
}
// CreateNotificationChannel 委托通知渠道创建。
func (r storeCommunicationRepository) CreateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow) (int64, error) {
return r.store.Notifications.CreateChannel(ctx, row)
}
// UpdateNotificationChannel 委托通知渠道更新。
func (r storeCommunicationRepository) UpdateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow, userID int64) error {
return r.store.Notifications.UpdateChannelForUser(ctx, row, userID)
}
// GetNotificationChannel 委托带用户归属的通知渠道查询。
func (r storeCommunicationRepository) GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) {
return r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID)
}
// DeleteNotificationChannel 委托通知渠道删除。
func (r storeCommunicationRepository) DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error {
return r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID)
}
// GetNotificationChannelConfig 委托通知渠道发送配置查询。
func (r storeCommunicationRepository) GetNotificationChannelConfig(ctx context.Context, channelID int64) (*db.NotificationChannel, error) {
return r.store.Notifications.GetChannel(ctx, channelID)
}
// ListNotificationBindings 委托通知绑定查询。
func (r storeCommunicationRepository) ListNotificationBindings(ctx context.Context, userID int64) ([]db.NotificationBindingRow, error) {
return r.store.Notifications.ListBindingsForUser(ctx, userID)
}
// SetNotificationBindings 委托通知绑定覆盖写入。
func (r storeCommunicationRepository) SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
return r.store.Notifications.SetBindings(ctx, cookieID, channelIDs)
}
// GetNotificationBindingIDs 委托账号通知绑定查询。
func (r storeCommunicationRepository) GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
return r.store.Notifications.AccountBindings(ctx, cookieID)
}
// SetSingleNotificationBinding 委托单个通知绑定状态更新。
func (r storeCommunicationRepository) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled)
}
// DeleteNotificationBinding 委托通知绑定删除。
func (r storeCommunicationRepository) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error {
return r.store.Notifications.DeleteBinding(ctx, userID, bindingID)
}
// DeleteAccountNotificationBindings 委托账号通知绑定删除。
func (r storeCommunicationRepository) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error {
return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)
}
// GetCookieValue 委托账号 Cookie 查询。
func (r storeCommunicationRepository) GetCookieValue(ctx context.Context, cookieID string) (string, error) {
return r.store.Cookies.GetValue(ctx, cookieID)
}
// UpdateCookieValue 委托账号 Cookie 更新。
func (r storeCommunicationRepository) UpdateCookieValue(ctx context.Context, cookieID, value string) error {
return r.store.Cookies.UpdateValueExisting(ctx, cookieID, value)
}
// MarkChatRead 委托聊天已读状态更新。
func (r storeCommunicationRepository) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error {
return r.store.Chats.MarkRead(ctx, userID, accountID, chatID)
}
// newStoreCommunicationRepository 从完整 Store 构造通信应用服务窄 repository。
func newStoreCommunicationRepository(store *db.Store) communicationRepository {
if store == nil || store.AccountTasks == nil || store.Notifications == nil || store.Cookies == nil || store.Chats == nil {
return nil
}
return storeCommunicationRepository{store: store}
}
// 确保 Store 适配器始终覆盖通信应用服务所需的全部能力。
var _ communicationRepository = storeCommunicationRepository{}
-381
View File
@@ -1,381 +0,0 @@
package server
import (
"context"
"errors"
"strings"
"xianyu-go/internal/account"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/automation"
domainchat "xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/xianyu/mtop"
)
var (
// errCommunicationUnavailable 表示聊天或自动化依赖尚未初始化。
errCommunicationUnavailable = errors.New("通信服务未启用")
)
// communicationService 是聊天、账号任务和通知应用服务。
type communicationService struct {
// server 提供数据库、聊天事件中心、账号运行时和通知器依赖。
server *Server
// repository 提供账号任务、通知绑定和聊天历史的最小持久化能力。
repository communicationRepository
}
// accountTaskUpdateInput 是账号任务设置更新的业务输入。
type accountTaskUpdateInput struct {
// CookieID 是账号标识。
CookieID string
// Settings 是待保存的任务设置。
Settings db.AccountTaskSettings
}
// notificationBindingRow 是通知绑定列表的一行业务数据。
type notificationBindingRow struct {
// ID 是绑定记录标识。
ID int64
// CookieID 是绑定账号标识。
CookieID string
// ChannelID 是通知渠道标识。
ChannelID int64
// ChannelName 是通知渠道名称。
ChannelName string
// Enabled 表示绑定是否启用。
Enabled bool
}
// communicationApplication 返回当前 Server 绑定的通信应用服务。
func (s *Server) communicationApplication() *communicationService {
return s.applicationServiceSet().communication
}
// GetAccountTaskSettings 读取指定账号的任务设置。
func (svc *communicationService) GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) {
return svc.repository.GetAccountTaskSettings(ctx, cookieID)
}
// UpdateAccountTaskSettings 校验并保存账号任务设置,然后返回数据库中的最终值。
func (svc *communicationService) UpdateAccountTaskSettings(ctx context.Context, input accountTaskUpdateInput) (db.AccountTaskSettings, error) {
// settings 是规范化后的账号任务设置。
settings := input.Settings
settings.CookieID = input.CookieID
settings.RateContent = strings.TrimSpace(settings.RateContent)
if settings.AutoRateEnabled && settings.RateContent == "" {
return db.AccountTaskSettings{}, errors.New("启用自动评价时评价内容不能为空")
}
if len([]rune(settings.RateContent)) > 500 {
return db.AccountTaskSettings{}, errors.New("评价内容不能超过 500 个字符")
}
if !accountTaskTimePattern.MatchString(settings.PolishTime) {
return db.AccountTaskSettings{}, errors.New("擦亮时间格式必须为 HH:mm")
}
// err 表示任务设置持久化错误。
if err := svc.repository.UpsertAccountTaskSettings(ctx, settings); err != nil {
return db.AccountTaskSettings{}, err
}
return svc.repository.GetAccountTaskSettings(ctx, input.CookieID)
}
// ListAccountTaskRuns 查询账号最近的任务执行记录。
func (svc *communicationService) ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) {
return svc.repository.ListAccountTaskRuns(ctx, cookieID, limit)
}
// RunAccountTask 执行一次账号自动化任务并返回执行摘要。
func (svc *communicationService) RunAccountTask(ctx context.Context, cookieID, taskType string) (automation.AccountTaskSummary, error) {
if svc.server.automation == nil {
return automation.AccountTaskSummary{}, errCommunicationUnavailable
}
return svc.server.automation.RunAccountTask(ctx, cookieID, taskType)
}
// ListNotificationChannels 查询用户拥有的通知渠道。
func (svc *communicationService) ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) {
return svc.repository.ListNotificationChannels(ctx, userID)
}
// CreateNotificationChannel 创建用户通知渠道。
func (svc *communicationService) CreateNotificationChannel(ctx context.Context, row db.NotificationChannelRow) (int64, error) {
return svc.repository.CreateNotificationChannel(ctx, &row)
}
// UpdateNotificationChannel 更新用户拥有的通知渠道。
func (svc *communicationService) UpdateNotificationChannel(ctx context.Context, row db.NotificationChannelRow, userID int64) error {
return svc.repository.UpdateNotificationChannel(ctx, &row, userID)
}
// GetNotificationChannel 查询用户拥有的单个通知渠道。
func (svc *communicationService) GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) {
return svc.repository.GetNotificationChannel(ctx, channelID, userID)
}
// DeleteNotificationChannel 删除用户拥有的通知渠道。
func (svc *communicationService) DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error {
return svc.repository.DeleteNotificationChannel(ctx, channelID, userID)
}
// TestNotificationChannel 向用户拥有的通知渠道发送测试消息。
func (svc *communicationService) TestNotificationChannel(ctx context.Context, channelID, userID int64, body string) error {
if svc.server.notifier == nil {
return errCommunicationUnavailable
}
// channel 和 err 保存通知渠道查询结果。
channel, err := svc.repository.GetNotificationChannelConfig(ctx, channelID)
if err != nil {
return err
}
if channel == nil {
return db.ErrForbidden
}
// row 和 err 保存带用户归属的渠道查询结果。
row, err := svc.repository.GetNotificationChannel(ctx, channelID, userID)
if err != nil {
return err
}
if row == nil {
return db.ErrForbidden
}
return svc.server.notifier.SendToChannel(channelID, body)
}
// ListNotificationBindings 查询用户账号的通知绑定。
func (svc *communicationService) ListNotificationBindings(ctx context.Context, userID int64) (map[string][]notificationBindingRow, error) {
// rows 和 err 保存绑定查询结果集。
rows, err := svc.repository.ListNotificationBindings(ctx, userID)
if err != nil {
return nil, err
}
// result 是按账号分组的通知绑定列表。
result := make(map[string][]notificationBindingRow)
// row 表示当前遍历过程中的row
for _, row := range rows {
// binding 保存当前扫描到的通知绑定记录。
binding := notificationBindingRow{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled}
result[binding.CookieID] = append(result[binding.CookieID], binding)
}
return result, nil
}
// SetNotificationBindings 覆盖保存账号的通知渠道绑定。
func (svc *communicationService) SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
return svc.repository.SetNotificationBindings(ctx, cookieID, channelIDs)
}
// GetNotificationBindingIDs 查询账号当前启用的通知渠道标识。
func (svc *communicationService) GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
return svc.repository.GetNotificationBindingIDs(ctx, cookieID)
}
// SetSingleNotificationBinding 更新单个账号通知渠道的启用状态。
func (svc *communicationService) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
if !enabled {
return svc.repository.SetSingleNotificationBinding(ctx, cookieID, channelID, false)
}
return svc.repository.SetSingleNotificationBinding(ctx, cookieID, channelID, true)
}
// DeleteNotificationBinding 删除用户账号下的一条通知绑定。
func (svc *communicationService) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error {
return svc.repository.DeleteNotificationBinding(ctx, userID, bindingID)
}
// DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。
func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error {
return svc.repository.DeleteAccountNotificationBindings(ctx, userID, cookieID)
}
// MarkChatRead 将指定聊天会话标记为已读。
func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error {
return svc.repository.MarkChatRead(ctx, userID, accountID, chatID)
}
// storeChatOutgoingRepository 将领域聊天服务适配为实时发送应用端口。
type storeChatOutgoingRepository struct {
// service 保存聊天消息幂等写入和实时事件发布能力。
service *domainchat.Service
}
// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) CreateOutgoing(ctx context.Context, session chatapp.Session, text string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的消息及写入错误。
message, err := r.service.CreateOutgoing(ctx, dbChatSessionFromApplication(session), text)
return applicationChatMessage(message), err
}
// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) CreateOutgoingMedia(ctx context.Context, session chatapp.Session, messageType, content string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的媒体消息及写入错误。
message, err := r.service.CreateOutgoingMedia(ctx, dbChatSessionFromApplication(session), messageType, content)
return applicationChatMessage(message), err
}
// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的状态消息及更新错误。
message, err := r.service.SetOutgoingStatus(ctx, accountID, key, status)
return applicationChatMessage(message), err
}
// managerChatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。
type managerChatSenderProvider struct {
// manager 保存当前进程内的账号运行时管理器。
manager *account.Manager
}
// Sender 返回指定账号的在线发送能力。
func (p managerChatSenderProvider) Sender(accountID string) (chatapp.Sender, bool) {
if p.manager == nil {
return nil, false
}
// sender、ok 保存账号管理器返回的运行时发送器及存在性。
sender, ok := p.manager.GetInstance(accountID)
if !ok || sender == nil {
return nil, false
}
return managerChatSender{sender: sender}, true
}
// managerChatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。
type managerChatSender struct {
// sender 保存账号运行时提供的最小消息发送能力。
sender automation.MessageSender
}
// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。
func (s managerChatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error {
return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text)
}
// SendImage 发送图片并将应用层幂等键传递给运行时接口。
func (s managerChatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error {
return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID)
}
// storeChatCredentialRepository 将账号 Cookie 仓储适配为图片发送端口。
type storeChatCredentialRepository struct {
// store 保存数据库聚合入口,仅在凭证适配器内读取和更新 Cookie。
store *db.Store
}
// GetCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。
func (r storeChatCredentialRepository) GetCookieValue(ctx context.Context, accountID string) (string, error) {
if r.store == nil || r.store.Cookies == nil {
return "", chatapp.ErrUnavailable
}
return r.store.Cookies.GetValue(ctx, accountID)
}
// UpdateCookieValue 保存图片上传后平台刷新的账号凭证。
func (r storeChatCredentialRepository) UpdateCookieValue(ctx context.Context, accountID, cookieValue string) error {
if r.store == nil || r.store.Cookies == nil {
return chatapp.ErrUnavailable
}
return r.store.Cookies.UpdateValueExisting(ctx, accountID, cookieValue)
}
// serverChatImageUploader 将 Server 当前 MTOP 客户端适配为图片上传端口。
type serverChatImageUploader struct {
// server 提供可动态替换的 MTOP 客户端,便于测试注入平台替身。
server *Server
// credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。
credentials storeChatCredentialRepository
// manager 负责将刷新后的凭证同步到在线运行时。
manager *account.Manager
}
// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。
func (u serverChatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) {
if u.server == nil {
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
}
// cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。
cookieValue, err := u.credentials.GetCookieValue(ctx, accountID)
if err != nil {
return chatapp.ImageUpload{}, err
}
// uploader、ok 保存 MTOP 图片上传能力及接口支持情况。
uploader, ok := u.server.mtopClient().(interface {
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
})
if !ok {
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
}
// upload、err 保存图片平台返回结果及调用错误。
upload, err := uploader.UploadChatImage(ctx, cookieValue, filename, contentType, data)
if err != nil {
return chatapp.ImageUpload{}, err
}
if upload == nil {
return chatapp.ImageUpload{}, chatapp.ErrSend
}
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookieValue {
// persistErr 保存刷新凭证的持久化错误;该错误必须反馈给调用方,避免静默丢失会话状态。
if persistErr := u.credentials.UpdateCookieValue(ctx, accountID, upload.UpdatedCookies); persistErr != nil {
return chatapp.ImageUpload{}, persistErr
}
if u.manager != nil {
// sender、senderOK 保存刷新凭证同步到运行时的结果。
sender, senderOK := u.manager.GetInstance(accountID)
if senderOK && sender != nil {
sender.UpdateCookie(upload.UpdatedCookies)
}
}
}
return chatapp.ImageUpload{URL: upload.URL}, nil
}
// newChatSendingApplication 创建实时聊天发送应用服务及其 Server 适配器。
func newChatSendingApplication(server *Server) *chatapp.Service {
// domainService 保存聊天领域服务;空值表示发送能力未装配。
var domainService *domainchat.Service
if server != nil {
domainService = server.chat
}
// store 保存聊天适配器可用的数据库入口;空 Server 仍返回可安全调用的不可用服务。
var store *db.Store
// manager 保存账号运行时管理器;空值表示无法发送平台消息。
var manager *account.Manager
if server != nil {
store, manager = server.Store, server.Manager
}
return chatapp.NewWithSending(
newStoreChatApplicationRepository(store),
storeChatOutgoingRepository{service: domainService},
managerChatSenderProvider{manager: manager},
serverChatImageUploader{server: server, credentials: storeChatCredentialRepository{store: store}, manager: manager},
)
}
// applicationChatMessage 将数据库消息转换为应用层模型;空指针保持零值。
func applicationChatMessage(message *db.ChatMessage) chatapp.Message {
if message == nil {
return chatapp.Message{}
}
return chatapp.Message{
ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, MessageKey: message.MessageKey,
Direction: message.Direction, SenderID: message.SenderID, SenderName: message.SenderName,
MessageType: message.MessageType, Content: message.Content, Status: message.Status, SentAt: message.SentAt,
}
}
// 确保各 Server 适配器覆盖聊天应用服务定义的最小端口。
var (
_ chatapp.OutgoingRepository = storeChatOutgoingRepository{}
_ chatapp.SenderProvider = managerChatSenderProvider{}
_ chatapp.Sender = managerChatSender{}
_ chatapp.ImageUploader = serverChatImageUploader{}
)
+9 -10
View File
@@ -4,18 +4,17 @@ import (
"context"
"testing"
"xianyu-go/internal/db"
automationapp "xianyu-go/internal/application/automation"
)
// TestCommunicationServiceUpdatesAccountTask 验证账号任务设置由通信应用服务校验并持久化。
func TestCommunicationServiceUpdatesAccountTask(t *testing.T) {
// TestAccountTaskApplicationUpdatesSettings 验证账号任务设置由独立应用服务校验并持久化。
func TestAccountTaskApplicationUpdatesSettings(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// settings 和 err 保存应用服务返回的最终任务设置。
settings, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{
CookieID: "acc1",
Settings: db.AccountTaskSettings{AutoRateEnabled: true, RateContent: " 好评 ", AutoPolishEnabled: false, PolishTime: "03:00"},
settings, err := srv.accountTaskApplication().UpdateSettings(context.Background(), automationapp.AccountTaskSettings{
CookieID: "acc1", AutoRateEnabled: true, RateContent: " 好评 ", AutoPolishEnabled: false, PolishTime: "03:00",
})
if err != nil {
t.Fatalf("UpdateAccountTaskSettings error: %v", err)
@@ -25,14 +24,14 @@ func TestCommunicationServiceUpdatesAccountTask(t *testing.T) {
}
}
// TestCommunicationServiceRejectsInvalidAccountTask 验证账号任务业务校验不依赖 HTTP 请求。
func TestCommunicationServiceRejectsInvalidAccountTask(t *testing.T) {
// TestAccountTaskApplicationRejectsInvalidSettings 验证账号任务业务校验不依赖 HTTP 请求。
func TestAccountTaskApplicationRejectsInvalidSettings(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// err 保存无效任务设置的校验错误。
_, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{
CookieID: "acc1", Settings: db.AccountTaskSettings{AutoRateEnabled: true, PolishTime: "03:00"},
_, err := srv.accountTaskApplication().UpdateSettings(context.Background(), automationapp.AccountTaskSettings{
CookieID: "acc1", AutoRateEnabled: true, PolishTime: "03:00",
})
if err == nil {
t.Fatal("启用自动评价但没有内容应该失败")
+159 -387
View File
@@ -3,7 +3,6 @@ package server
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
@@ -12,11 +11,9 @@ import (
"github.com/go-chi/chi/v5"
accountapp "xianyu-go/internal/application/account"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/xianyu/cookierefresh"
xrenew "xianyu-go/internal/xianyu/renew"
)
// mountCookies 账号 cookie 管理端点。
@@ -45,47 +42,18 @@ func (s *Server) mountCookies(r chi.Router) {
func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
// ownedDetail、ok 保存账号摘要和归属校验结果。
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
// result 保存应用服务返回的不含凭证的长登录状态。
result, err := s.accountLongLoginApplication().Query(r.Context(), ownedDetail.UserID, cid)
if err != nil {
s.writeLongLoginError(w, err)
return
}
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := scopedCookieHeader(detail, xrenew.QueryLoginSettingsURL)
// result 保存结果,供当前处理流程使用
var result *xrenew.LongLoginSettings
// requestErr 保存请求Err,供当前处理流程使用
var requestErr error
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies, snapshot)
} else {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies)
}
// credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
return
}
if credentialChanged {
s.updateRunningCookie(r.Context(), cid, result.NewCookies)
}
if requestErr != nil {
writeErr(w, http.StatusBadGateway, requestErr.Error())
return
}
writeJSON(w, http.StatusOK, result)
writeJSON(w, http.StatusOK, longLoginResponse{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled})
}
// setLongLoginSettings 负责setLong登录设置相关处理。
@@ -106,98 +74,30 @@ func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
// result 保存应用服务返回的不含凭证的长登录状态。
result, err := s.accountLongLoginApplication().Set(r.Context(), ownedDetail.UserID, cid, *req.Enabled)
if err != nil {
s.writeLongLoginError(w, err)
return
}
writeJSON(w, http.StatusOK, longLoginResponse{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled})
}
// writeLongLoginError 将长登录应用错误映射为兼容现有客户端的 HTTP 状态。
func (s *Server) writeLongLoginError(w http.ResponseWriter, err error) {
if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) || errors.Is(err, accountapp.ErrCredentialNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := scopedCookieHeader(detail, xrenew.SetLoginSettingsURL)
// result 保存结果,供当前处理流程使用
var result *xrenew.LongLoginSettings
// requestErr 保存请求Err,供当前处理流程使用
var requestErr error
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled, snapshot)
} else {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled)
}
// credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
if errors.Is(err, accountapp.ErrLongLoginPlatform) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
writeErr(w, http.StatusBadGateway, err.Error())
return
}
if credentialChanged {
s.updateRunningCookie(r.Context(), cid, result.NewCookies)
}
if requestErr != nil {
writeErr(w, http.StatusBadGateway, requestErr.Error())
if strings.Contains(err.Error(), "平台") || strings.Contains(err.Error(), "HTTP") {
writeErr(w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
// persistLongLoginCookies 必须在账号凭证锁内调用。它只更新持久化状态;
// 运行中实例的 Cookie 更新必须等调用方释放凭证锁后再执行。
// persistLongLoginCookies 负责persistLong登录Cookies相关处理。
func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) {
if result == nil || detail == nil {
return false, nil
}
// metadata 保存metadata,供当前处理流程使用
metadata := detail.MetadataJSON
// snapshot、hasSnapshot 保存snapshot、hasSnapshot,供当前处理流程使用
snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if result.CookieSnapshotComplete {
snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
)
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
} else if hasSnapshot {
// 兼容非标准 Service 实现:只有未返回最终 Jar 时才按当前请求 URL
// 应用响应头;官方 Service 会在 SET→QUERY 间逐请求维护完整 Jar。
snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), "https://goofish.com")
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
)
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
} else {
// 历史账号只有扁平 Cookie 时只能合并兼容值,不能凭空推断完整
// Domain/Path/HttpOnly/PartitionKey 属性。
result.NewCookies = xrenew.MergeSetCookies(detail.Value, result.SetCookies)
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
}
// credentialChanged 保存credentialChanged,供当前处理流程使用
credentialChanged := result.NewCookies != detail.Value || metadata != detail.MetadataJSON
if !credentialChanged && len(result.SetCookies) == 0 {
return false, nil
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err)
return false, err
}
if credentialChanged && s.Store.Tokens != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil {
s.Logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", err)
}
}
return credentialChanged, nil
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
}
// updateRunningCookie 负责updateRunning登录凭证相关处理。
@@ -216,30 +116,20 @@ func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string
// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。
func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
if s == nil || s.Store == nil || s.Store.Automation == nil {
if s == nil {
return
}
// service 提供凭证恢复后的自动化任务唤醒能力。
service := s.credentialWakeApplication()
if service == nil {
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
err := service.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil {
s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
}
}
// scopedCookieHeader 负责scoped登录凭证Header相关处理。
func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string {
if detail == nil {
return ""
}
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
if // header、authoritative 保存header、authoritative,供当前处理流程使用
header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative {
return header
}
}
return detail.Value
}
// updateCookieSettingsRequest 保存update登录凭证设置请求,供当前处理流程使用
type updateCookieSettingsRequest struct {
Cookie *string `json:"cookie"`
@@ -258,7 +148,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// detail、ok 保存detail、ok,供当前处理流程使用
detail, ok := s.requireCookieSecretOwner(w, r, cid)
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
@@ -286,91 +176,49 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latestDetail、err 保存latestDetail、err,供当前处理流程使用
latestDetail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || latestDetail == nil || latestDetail.UserID != detail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
// password 保存待写入的登录密码;nil 表示保留已有密码,空字符串指令表示清除密码。
var password *string
if req.LoginPassword != nil && *req.LoginPassword != "" {
password = req.LoginPassword
}
detail = latestDetail
// input 保存input,供当前处理流程使用
input := db.AccountSettingsUpdate{
UserID: detail.UserID,
Value: req.Cookie,
Remark: req.Remark,
AutoConfirm: req.AutoConfirm,
PauseDuration: req.PauseDuration,
ChannelIDs: req.ChannelIDs,
if req.ClearPassword {
// clearedPassword 是明确清除登录密码的空值指令,不读取既有秘密。
clearedPassword := ""
password = &clearedPassword
}
// loginChanged 保存登录Changed,供当前处理流程使用
loginChanged := req.Username != nil || req.LoginPassword != nil || req.ShowBrowser != nil || req.ClearPassword
if loginChanged {
// username 保存username,供当前处理流程使用
username := detail.Username
if req.Username != nil {
username = *req.Username
}
// password 保存密码,供当前处理流程使用
password := detail.Password
if req.LoginPassword != nil && *req.LoginPassword != "" {
password = *req.LoginPassword
}
if req.ClearPassword {
password = ""
}
// showBrowser 保存show浏览器,供当前处理流程使用
showBrowser := detail.ShowBrowser
if req.ShowBrowser != nil {
showBrowser = *req.ShowBrowser
}
input.Username = &username
input.Password = &password
input.ShowBrowser = &showBrowser
}
// pausedUntil、err 保存pausedUntil、err,供当前处理流程使用
pausedUntil, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, input)
// settingsResult、err 保存应用服务返回的暂停截止时间、补偿错误和主写入错误。
settingsResult, err := s.accountSettingsApplication().UpdateSettings(r.Context(), accountapp.SettingsUpdateInput{
UserID: ownedDetail.UserID, AccountID: cid, Cookie: req.Cookie, Remark: req.Remark,
AutoConfirm: req.AutoConfirm, PauseDuration: req.PauseDuration, Username: req.Username,
Password: password, ShowBrowser: req.ShowBrowser, ChannelIDs: req.ChannelIDs,
})
if err != nil {
credentialUnlock()
switch {
case errors.Is(err, db.ErrForbidden):
case errors.Is(err, accountapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "账号设置包含无权限使用的资源")
case errors.Is(err, db.ErrNotFound):
case errors.Is(err, accountapp.ErrNotFound):
writeErr(w, http.StatusNotFound, "账号不存在")
default:
writeErr(w, http.StatusBadRequest, err.Error())
}
return
}
if req.Cookie != nil {
// UpdateSettings 已在同一事务中写入 Cookie 并清除旧快照,不能再做
// 第二次非原子覆盖。
if s.Store.Tokens != nil {
if // err 保存err,供当前处理流程使用
err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", err)
}
}
if settingsResult.TokenCleanupError != nil && s.Logger != nil {
s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", settingsResult.TokenCleanupError)
}
credentialUnlock()
if req.Cookie != nil && s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if // err 保存err,供当前处理流程使用
err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
}
if settingsResult.RuntimeError != nil && s.Logger != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", settingsResult.RuntimeError)
}
writeJSON(w, http.StatusOK, cookieSettingsResponse{
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
Success: true, PausedUntil: settingsResult.PausedUntil, Paused: settingsResult.PausedUntil > time.Now().UTC().Unix(),
})
}
// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API,可安全用于前端轮询。
func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
cookieIDs, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
accountSummary := s.accountSummaryApplication()
cookieIDs, err := accountSummary.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。
if err != nil {
writeErr(w, http.StatusInternalServerError, "获取账号失败")
return
@@ -381,7 +229,8 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request)
}
result := make(map[string]engine.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。
for _, cid := range cookieIDs { // cid 是当前账号 ID。
if !s.Store.Cookies.GetStatus(r.Context(), cid) {
enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid)
if statusErr != nil || !enabled {
result[cid] = engine.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
continue
}
@@ -396,8 +245,8 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request)
// listCookies 列出当前用户的 cookie_id。
func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
ids, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // ids 和 err 是账号 ID 列表及查询错误。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
ids, err := s.accountSummaryApplication().ListOwnedIDs(r.Context(), sess.UserID) // ids 和 err 是账号 ID 列表及查询错误。
if err != nil {
writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败")
return
@@ -407,19 +256,30 @@ func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) {
// listCookieDetails 账号非敏感详情(不含 cookie 明文/密码,遵循 Fork 安全基线)。
func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
summaries, err := s.Store.Cookies.ListSummaries(r.Context(), sess.UserID) // summaries 和 err 是账号摘要及查询错误。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
summaries, err := s.accountSummaryApplication().ListSummaries(r.Context(), sess.UserID) // summaries 和 err 是账号摘要及查询错误。
if err != nil {
writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败")
return
}
result := make([]cookieSummaryResponse, 0, len(summaries)) // result 是非敏感详情响应列表。
for _, summary := range summaries { // summary 是当前账号的非敏感摘要。
tasks, _ := s.Store.AccountTasks.Get(r.Context(), summary.ID) // tasks 是当前账号的自动化任务设置。
// tasks 保存通过账号任务应用 Port 读取的非敏感任务设置。
tasks := automationapp.AccountTaskSettings{CookieID: summary.ID}
// service 提供账号任务设置的应用层查询能力。
if service := s.accountTaskApplication(); service != nil {
// loadedTasks、taskErr 保存应用层任务设置及读取错误;旧接口读取失败时仍保留默认值。
loadedTasks, taskErr := service.GetSettings(r.Context(), summary.ID)
if taskErr == nil {
tasks = loadedTasks
}
}
// enabled、statusErr 保存当前账号启用状态及查询错误。
enabled, statusErr := s.accountSummaryApplication().StatusOwned(r.Context(), sess.UserID, summary.ID)
result = append(result, cookieSummaryResponse{
ID: summary.ID,
HasCookie: true,
Enabled: s.Store.Cookies.GetStatus(r.Context(), summary.ID),
Enabled: statusErr == nil && enabled,
AutoConfirm: summary.AutoConfirm,
Remark: summary.Remark,
PauseDuration: summary.PauseDuration,
@@ -447,16 +307,27 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
// getCookieDetails 单个账号非敏感详情。
func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
summary, err := s.Store.Cookies.GetSummaryOwned(r.Context(), sess.UserID, cid) // summary 和 err 是账号摘要及查询错误。
cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
summary, err := s.accountSummaryApplication().GetOwnedSummary(r.Context(), sess.UserID, cid) // summary 和 err 是账号摘要及查询错误。
if err != nil {
writeErr(w, http.StatusForbidden, "无权限操作该Cookie")
return
}
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid) // tasks 是当前账号的自动化任务设置。
// tasks 保存通过账号任务应用 Port 读取的非敏感任务设置。
tasks := automationapp.AccountTaskSettings{CookieID: cid}
// service 提供账号任务设置的应用层查询能力。
if service := s.accountTaskApplication(); service != nil {
// loadedTasks、taskErr 保存应用层任务设置及读取错误;旧接口读取失败时仍保留默认值。
loadedTasks, taskErr := service.GetSettings(r.Context(), cid)
if taskErr == nil {
tasks = loadedTasks
}
}
// enabled、statusErr 保存当前账号启用状态及查询错误。
enabled, statusErr := s.accountSummaryApplication().StatusOwned(r.Context(), sess.UserID, cid)
writeJSON(w, http.StatusOK, cookieDetailResponse{
ID: summary.ID, Enabled: s.Store.Cookies.GetStatus(r.Context(), cid), AutoConfirm: summary.AutoConfirm,
ID: summary.ID, Enabled: statusErr == nil && enabled, AutoConfirm: summary.AutoConfirm,
Remark: summary.Remark, PauseDuration: summary.PauseDuration, PausedUntil: summary.PausedUntil,
Paused: summary.PausedUntil > time.Now().UTC().Unix(), ShowBrowser: summary.ShowBrowser,
Username: summary.Username, Nickname: cachedCookieSummaryNickname(summary), AvatarURL: summary.AvatarURL,
@@ -540,11 +411,11 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
return
}
if errors.Is(err, db.ErrAlreadyExists) {
if errors.Is(err, accountapp.ErrAlreadyExists) {
writeErr(w, http.StatusConflict, "该账号ID已存在,请使用更新账号功能")
return
}
@@ -588,7 +459,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusConflict, err.Error())
return
}
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
@@ -602,8 +473,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
// detail、ok 保存detail、ok,供当前处理流程使用
detail, ok := s.requireCookieSecretOwner(w, r, cid)
// detail、ok 保存非敏感账号摘要和归属校验结果。
detail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
@@ -620,18 +491,20 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// password 保存密码,供当前处理流程使用
password := req.Password
if password == "" {
password = req.LoginPassword
// password 保存待写入的登录密码;nil 表示兼容地保留既有密码。
passwordValue := req.Password
if passwordValue == "" {
passwordValue = req.LoginPassword
}
if req.ClearPassword {
password = ""
} else if password == "" && detail != nil {
password = detail.Password
// password 保存可选登录密码指针;nil 表示保留数据库中的既有秘密。
var password *string
if passwordValue != "" || req.ClearPassword {
password = &passwordValue
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
// err 保存应用层登录信息写入错误。
if err := s.accountSettingsApplication().UpdateLoginInfo(r.Context(), accountapp.LoginInfoUpdateInput{
UserID: detail.UserID, AccountID: cid, Username: req.Username, Password: password, ShowBrowser: req.ShowBrowser,
}); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
@@ -656,40 +529,22 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// reason 保存原因,供当前处理流程使用
reason := ""
if !req.Enabled {
reason = db.DisableReasonManual
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil {
credentialUnlock()
// result、err 保存应用层启停结果和持久化错误。
result, err := s.accountSettingsApplication().SetStatus(r.Context(), ownedDetail.UserID, cid, req.Enabled)
if err != nil {
if errors.Is(err, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
if errors.Is(err, accountapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
credentialUnlock()
// 启停引擎实例。
if s.Manager != nil {
if req.Enabled {
// 重启拉取最新 cookie。
if _, e := s.loadCookiePlatformDetail(r.Context(), cid); e == nil {
if // err 保存err,供当前处理流程使用
err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("启用后重启账号失败", "cookie_id", cid, "err", err)
}
}
} else {
s.Manager.Stop(cid)
}
if result.RuntimeError != nil && s.Logger != nil {
s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError)
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
@@ -725,7 +580,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
if errors.Is(deleteErr, accountapp.ErrNotFound) || errors.Is(deleteErr, db.ErrNotFound) {
if errors.Is(deleteErr, accountapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
@@ -735,7 +590,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
}
s.Logger.Info("账号已删除",
"cookie_id", cid,
"nickname", cachedAccountNickname(ownedDetail),
"nickname", cachedAccountSummaryNickname(ownedDetail),
"user_id", ownedDetail.UserID,
)
writeJSON(w, http.StatusOK, operationResponse{Success: true})
@@ -757,12 +612,14 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
// sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。
sess := authSess(r)
if // err 保存err,供当前处理流程使用
_, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
UserID: sess.UserID, AutoConfirm: &req.AutoConfirm,
}); err != nil {
if // err 保存应用层自动确认设置错误。
_, err := s.accountSettingsApplication().SetAutoConfirm(r.Context(), sess.UserID, cid, req.AutoConfirm); err != nil {
if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败")
return
}
@@ -797,12 +654,14 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
// sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。
sess := authSess(r)
if // err 保存err,供当前处理流程使用
_, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
UserID: sess.UserID, Remark: &req.Remark,
}); err != nil {
if // err 保存应用层账号备注错误。
_, err := s.accountSettingsApplication().SetRemark(r.Context(), sess.UserID, cid, req.Remark); err != nil {
if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
writeErr(w, http.StatusInternalServerError, "保存账号备注失败")
return
}
@@ -829,14 +688,20 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, "暂停时长必须在 0 到 1440 分钟之间")
return
}
// pausedUntil、err 保存pausedUntil、err,供当前处理流程使用
pausedUntil, err := s.Store.Cookies.SetPause(r.Context(), cid, req.PauseDuration)
// sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。
sess := authSess(r)
// result、err 保存应用层暂停设置结果和错误。
result, err := s.accountSettingsApplication().SetPause(r.Context(), sess.UserID, cid, req.PauseDuration)
if err != nil {
if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
writeErr(w, http.StatusInternalServerError, "保存暂停时长失败")
return
}
writeJSON(w, http.StatusOK, cookieSettingsResponse{
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
Success: true, PausedUntil: result.PausedUntil, Paused: result.PausedUntil > time.Now().UTC().Unix(),
})
}
@@ -847,117 +712,24 @@ func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request)
if !s.requireCookieOwnership(w, r, cid) {
return
}
// paused、pausedUntil 保存paused、pausedUntil,供当前处理流程使用
paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid)
// sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。
sess := authSess(r)
// pauseState 保存应用层返回的非敏感暂停状态。
pauseState, _ := s.accountSettingsApplication().GetPause(r.Context(), sess.UserID, cid)
writeJSON(w, http.StatusOK, pauseDurationResponse{
PauseDuration: s.Store.Cookies.GetPauseDuration(r.Context(), cid), PausedUntil: pausedUntil, Paused: paused,
PauseDuration: pauseState.Duration, PausedUntil: pauseState.PausedUntil, Paused: pauseState.Paused,
})
}
// refreshAccountProfile 刷新账号平台资料并返回展示字段。
// 该流程按需读取平台凭证,调用方负责所有权校验。
// refreshAccountProfile 负责refresh账号Profile相关处理。
func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) {
if d == nil {
return "", "", ""
// cachedAccountSummaryNickname 从非敏感应用摘要生成删除日志展示名,不构造或读取数据库凭证模型。
func cachedAccountSummaryNickname(summary accountapp.AccountSummary) string {
if strings.TrimSpace(summary.Remark) != "" {
return strings.TrimSpace(summary.Remark)
}
if s.MTop == nil {
return cachedAccountNickname(d), d.AvatarURL, "账号资料客户端未初始化"
if strings.TrimSpace(summary.Nickname) != "" {
return strings.TrimSpace(summary.Nickname)
}
// repository 提供资料刷新所需的凭证锁、平台视图和资料持久化能力。
repository := s.accountLoginRepositoryForServer()
if repository == nil {
return cachedAccountNickname(d), d.AvatarURL, "账号登录持久化未初始化"
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := repository.LockCredentials(d.ID)
// latest、latestErr 保存latest、latestErr,供当前处理流程使用
latest, latestErr := repository.LoadPlatformDetail(ctx, d.ID)
if latestErr != nil || latest == nil || latest.UserID != d.UserID {
credentialUnlock()
if latestErr == nil {
latestErr = db.ErrNotFound
}
return cachedAccountNickname(d), d.AvatarURL, truncate(latestErr.Error(), 180)
}
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
// profile、callErr 保存profile、callErr,供当前处理流程使用
profile, callErr := s.MTop.FetchUserProfile(mtopCtx, latest.Value)
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
// runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用
runtimeCookieChanged := false
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存账号资料响应 Cookie Jar 失败", "account", d.ID, "err", persistErr)
}
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr))
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
d.Value = value
} else if callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != latest.Value {
// 注入 mock 或没有权威快照的历史账号继续沿用扁平 Cookie 路径;
// 该路径必须清除旧 snapshot,不能伪造完整 Jar。
if // err 保存err,供当前处理流程使用
err := repository.UpdateFlatCookieOwned(ctx, latest, profile.UpdatedCookies); err != nil {
if s.Logger != nil {
s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
}
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", err))
} else {
runtimeCookie = profile.UpdatedCookies
runtimeCookieChanged = true
d.Value = profile.UpdatedCookies
}
}
credentialUnlock()
if runtimeCookieChanged {
s.updateRunningCookie(ctx, d.ID, runtimeCookie)
}
if callErr != nil {
s.recoverExpiredMTOPSession(ctx, d.ID, callErr)
if s.Logger != nil {
s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", callErr)
}
return cachedAccountNickname(d), d.AvatarURL, truncate(callErr.Error(), 180)
}
if profile == nil {
return cachedAccountNickname(d), d.AvatarURL, "账号资料接口未返回结果"
}
// apiNickname 保存apiNickname,供当前处理流程使用
apiNickname := strings.TrimSpace(profile.Nickname)
// apiAvatarURL 保存apiAvatarURL,供当前处理流程使用
apiAvatarURL := normalizeProfileAvatarURL(profile.AvatarURL)
if // err 保存err,供当前处理流程使用
err := repository.UpdateProfile(ctx, d.ID, apiNickname, apiAvatarURL); err != nil && s.Logger != nil {
s.Logger.Warn("保存账号资料失败", "account", d.ID, "err", err)
}
if apiNickname == "" {
apiNickname = cachedAccountNickname(d)
}
if apiAvatarURL == "" {
apiAvatarURL = d.AvatarURL
}
return apiNickname, apiAvatarURL, ""
}
// cachedAccountNickname 负责cached账号Nickname相关处理。
func cachedAccountNickname(d *db.CookieDetail) string {
if strings.TrimSpace(d.Remark) != "" {
return strings.TrimSpace(d.Remark)
}
if strings.TrimSpace(d.Nickname) != "" {
return strings.TrimSpace(d.Nickname)
}
return "账号 " + truncate(d.ID, 6)
return "账号 " + truncate(summary.ID, 6)
}
// normalizeProfileAvatarURL 负责normalizeProfileAvatarURL相关处理。
@@ -984,7 +756,7 @@ func truncate(s string, n int) string {
}
// cachedCookieSummaryNickname 根据账号摘要生成展示名称,不依赖敏感凭证字段。
func cachedCookieSummaryNickname(summary db.CookieSummary) string {
func cachedCookieSummaryNickname(summary accountapp.AccountSummary) string {
if strings.TrimSpace(summary.Remark) != "" {
return strings.TrimSpace(summary.Remark)
}
+17
View File
@@ -12,12 +12,24 @@ import (
"testing"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
xrenew "xianyu-go/internal/xianyu/renew"
)
// cachedAccountNickname 保留测试对账号展示名兼容规则的独立验证,不参与生产 HTTP 路径。
func cachedAccountNickname(d *db.CookieDetail) string {
if strings.TrimSpace(d.Remark) != "" {
return strings.TrimSpace(d.Remark)
}
if strings.TrimSpace(d.Nickname) != "" {
return strings.TrimSpace(d.Nickname)
}
return "账号 " + truncate(d.ID, 6)
}
// seedStaleCookieSnapshot 负责seedStale登录凭证Snapshot相关处理。
func seedStaleCookieSnapshot(t *testing.T, store *db.Store, cookieID string) {
t.Helper()
@@ -1172,6 +1184,11 @@ func TestCachedAccountNickname(t *testing.T) {
if got != c.want {
t.Errorf("cachedAccountNickname(remark=%q,nick=%q,id=%q)=%q want %q", c.remark, c.nickname, c.id, got, c.want)
}
// summaryGot 保存非敏感应用摘要生成的展示名,验证摘要边界与兼容模型保持同样的日志语义。
summaryGot := cachedAccountSummaryNickname(accountapp.AccountSummary{ID: c.id, Nickname: c.nickname, Remark: c.remark})
if summaryGot != c.want {
t.Errorf("cachedAccountSummaryNickname(remark=%q,nick=%q,id=%q)=%q want %q", c.remark, c.nickname, c.id, summaryGot, c.want)
}
}
}
@@ -0,0 +1,9 @@
package server
import defaultreplyapp "xianyu-go/internal/application/defaultreply"
// defaultReplyApplication 返回默认回复应用服务。
// 该方法在主装配集合接入前提供同一 Port 的兼容构造入口,后续由统一装配复用实例。
func (s *Server) defaultReplyApplication() *defaultreplyapp.Service {
return s.applicationServiceSet().defaultReplies
}
+96 -39
View File
@@ -1,12 +1,13 @@
package server
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// btoi bool→int(SQLite 无原生 bool)。
@@ -40,69 +41,94 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
// getDefaultReply 负责getDefault回复相关处理。
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 是路径中的默认回复所属账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。
userID, ok := defaultReplyUserID(w, r)
if !ok {
return
}
// dr、err 保存dr、err,供当前处理流程使用
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
if err != nil {
// reply、err 保存应用服务返回的默认回复模型及读取错误。
reply, err := s.defaultReplyApplication().Get(r.Context(), userID, cid)
switch {
case errors.Is(err, defaultreplyapp.ErrConfigNotFound):
writeJSON(w, http.StatusOK, defaultReplyResponse{Enabled: false, ReplyContent: "", ReplyOnce: false})
return
case errors.Is(err, defaultreplyapp.ErrAccountNotFound):
writeErr(w, http.StatusNotFound, "账号不存在")
return
case errors.Is(err, defaultreplyapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
case err != nil:
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// 已保存默认回复通过具名 DTO 返回,单账号查询不填充 cookie_id。
writeJSON(w, http.StatusOK, newDefaultReplyResponse("", *dr))
writeJSON(w, http.StatusOK, newDefaultReplyResponse("", reply))
}
// setDefaultReply 保存指定账号的默认回复配置。
func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
// cid 是当前操作的账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。
userID, ok := defaultReplyUserID(w, r)
if !ok {
return
}
// req 是默认回复配置请求体。
var req struct {
Enabled bool `json:"enabled"`
ReplyContent string `json:"reply_content"`
ReplyImageURL string `json:"reply_image_url"`
ReplyOnce bool `json:"reply_once"`
}
// err 是请求体解码错误。
if err := decodeJSON(r, &req); err != nil {
var req defaultReplyMutationRequest
// decodeErr 表示请求体不是有效的默认回复 JSON。
if decodeErr := decodeJSON(r, &req); decodeErr != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// err 是默认回复写入错误。
err := s.Store.DefaultReps.Upsert(r.Context(), cid, db.DefaultReply{
// err 表示默认回复应用服务写入失败的原因。
err := s.defaultReplyApplication().Upsert(r.Context(), userID, cid, defaultreplyapp.Reply{
Enabled: req.Enabled, ReplyContent: req.ReplyContent,
ReplyImageURL: req.ReplyImageURL, ReplyOnce: req.ReplyOnce,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
writeDefaultReplyMutationError(w, err, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// defaultReplyMutationRequest 是默认回复配置写入接口的具名请求 DTO。
type defaultReplyMutationRequest struct {
// Enabled 表示是否启用默认回复。
Enabled bool `json:"enabled"`
// ReplyContent 是默认回复文字内容。
ReplyContent string `json:"reply_content"`
// ReplyImageURL 是默认回复图片地址。
ReplyImageURL string `json:"reply_image_url"`
// ReplyOnce 表示同一聊天是否只发送一次默认回复。
ReplyOnce bool `json:"reply_once"`
}
// listDefaultReplies 查询当前用户的默认回复列表。
func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
// sess 是当前登录用户会话。
sess := auth.SessionFromContext(r.Context())
// rows 和 err 是当前用户的默认回复列表及查询错误。
rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// rows 和 err 是当前用户的应用层默认回复列表及查询错误。
rows, err := s.defaultReplyApplication().List(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 是默认回复列表响应。
var out []defaultReplyResponse
// row 表示当前遍历过程中的row
// row 表示当前遍历过程中的应用层默认回复摘要。
for _, row := range rows {
out = append(out, defaultReplyResponse{
CookieID: row.CookieID, Enabled: row.Enabled, ReplyContent: row.ReplyContent, ReplyOnce: row.ReplyOnce,
ReplyImageURL: row.ReplyImageURL,
CookieID: row.CookieID, Enabled: row.Reply.Enabled, ReplyContent: row.Reply.ReplyContent,
ReplyOnce: row.Reply.ReplyOnce, ReplyImageURL: row.Reply.ReplyImageURL,
// 列表 DTO 保留账号标识,前端可直接建立按账号索引。
})
}
@@ -113,22 +139,26 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
// sess 是当前登录用户会话。
sess := auth.SessionFromContext(r.Context())
// rows 和 err 是当前用户的默认回复列表及查询错误。
rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// rows 和 err 是当前用户的应用层默认回复列表及查询错误。
rows, err := s.defaultReplyApplication().List(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 是按账号标识索引的默认回复映射。
out := make(map[string]defaultReplyResponse)
// row 表示当前遍历过程中的row
// row 表示当前遍历过程中的应用层默认回复摘要。
for _, row := range rows {
out[row.CookieID] = defaultReplyResponse{
CookieID: row.CookieID,
Enabled: row.Enabled,
ReplyContent: row.ReplyContent,
ReplyOnce: row.ReplyOnce,
ReplyImageURL: row.ReplyImageURL,
Enabled: row.Reply.Enabled,
ReplyContent: row.Reply.ReplyContent,
ReplyOnce: row.Reply.ReplyOnce,
ReplyImageURL: row.Reply.ReplyImageURL,
// map 键与 cookie_id 同时保留,兼容旧前端索引方式。
}
}
@@ -139,13 +169,15 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
// cid 是当前操作的账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。
userID, ok := defaultReplyUserID(w, r)
if !ok {
return
}
// err 是默认回复删除错误。
err := s.Store.DefaultReps.Delete(r.Context(), cid)
// err 表示默认回复应用服务删除失败的原因。
err := s.defaultReplyApplication().Delete(r.Context(), userID, cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
writeDefaultReplyMutationError(w, err, "删除失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
@@ -155,13 +187,38 @@ func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) {
// cid 是当前操作的账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。
userID, ok := defaultReplyUserID(w, r)
if !ok {
return
}
// err 是默认回复记录清理错误。
if err := s.Store.DefaultReps.ClearRecords(r.Context(), cid); err != nil {
writeErr(w, http.StatusInternalServerError, "清空失败")
// err 表示默认回复应用服务清理投递记录失败的原因。
if err := s.defaultReplyApplication().ClearRecords(r.Context(), userID, cid); err != nil {
writeDefaultReplyMutationError(w, err, "清空失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// defaultReplyUserID 从认证上下文读取当前用户,并统一处理缺失会话。
func defaultReplyUserID(w http.ResponseWriter, r *http.Request) (int64, bool) {
// session 是认证中间件写入请求上下文的当前用户会话。
session := auth.SessionFromContext(r.Context())
if session == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return 0, false
}
return session.UserID, true
}
// writeDefaultReplyMutationError 将默认回复应用错误映射为既有 HTTP 错误语义。
func writeDefaultReplyMutationError(w http.ResponseWriter, err error, fallback string) {
switch {
case errors.Is(err, defaultreplyapp.ErrAccountNotFound):
writeErr(w, http.StatusNotFound, "账号不存在")
case errors.Is(err, defaultreplyapp.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权限操作该账号")
default:
writeErr(w, http.StatusInternalServerError, fallback)
}
}
+2 -2
View File
@@ -474,7 +474,7 @@ func TestOrderImportReportsPartialFailure(t *testing.T) {
// TestAdminEndpoints 管理员统计 + 用户列表 + 非 admin 被拒。
func TestAdminEndpoints(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
@@ -512,7 +512,7 @@ func TestAdminEndpoints(t *testing.T) {
}
// 创建普通用户验证 admin 隔离。
srv.Store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
// 普通用户不应能访问 admin(需单独登录验证,此处仅验证 admin 能看到)。
req3 := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
req3.AddCookie(cookie)
+2 -2
View File
@@ -145,13 +145,13 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) {
// TestAdminEndpointRejectsNonAdmin 非 admin 用户访问管理端点应 403。
func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
// 创建普通用户并登录。
srv.Store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
// body 保存请求体,供当前处理流程使用
body := `{"username":"user2","password":"pw"}`
// req 保存req,供当前处理流程使用
+4 -3
View File
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
@@ -207,14 +208,14 @@ func TestPublicHTTPClient(t *testing.T) {
// TestPublishBatchToMap 批次转具名 DTO 序列化并校验状态计数。
func TestPublishBatchToMap(t *testing.T) {
// batch 保存批次,供当前处理流程使用
batch := &db.ItemPublishBatch{ID: "b1", Status: "running", Filename: "x.csv"}
batch := itemapp.BatchInfo{ID: "b1", Status: "running", Filename: "x.csv"}
// rows 保存rows,供当前处理流程使用
rows := []db.ItemPublishBatchRow{
rows := []itemapp.BatchRow{
{ID: 1, RowNo: 1, CookieID: "c1", Title: "t1", Status: "pending", ImagesJSON: `["a.png"]`},
{ID: 2, RowNo: 2, CookieID: "c1", Title: "t2", Status: "running"},
}
// m 保存m,供当前处理流程使用
m := publishBatchToMap(batch, rows)
m := publishBatchApplicationToResponse(batch, rows)
if m.ID != "b1" || m.Status != "running" {
t.Fatalf("batch 字段异常: %+v", m)
}
-14
View File
@@ -1,14 +0,0 @@
package server
import (
"net/http"
"time"
)
// init 负责init相关处理。
func init() {
// 服务器单测通过 httptest 模拟 AI 端点;生产构造器仍使用 netguard。
newSettingsOutboundHTTPClient = func(string) (*http.Client, error) {
return &http.Client{Timeout: 20 * time.Second}, nil
}
}
@@ -0,0 +1,26 @@
package server
import (
"context"
itemapp "xianyu-go/internal/application/items"
)
// newBatchLocalPublishService 返回构造阶段已完成依赖校验的批量本地收口应用服务。
func (s *Server) newBatchLocalPublishService() (*itemapp.BatchLocalPublishService, error) {
if s == nil || s.applicationServiceSet() == nil || s.applicationServiceSet().itemBatchLocalPublish == nil {
return nil, itemapp.ErrBatchLocalPublishUnavailable
}
return s.applicationServiceSet().itemBatchLocalPublish, nil
}
// createPublishAutomationRules 保留旧测试入口,但实际规则编排已由应用服务负责。
func (s *Server) createPublishAutomationRules(ctx context.Context, userID int64, row itemapp.BatchRow, result *itemapp.BatchPublishResult) error {
// service 保存已装配的批量本地收口应用服务。
service, err := s.newBatchLocalPublishService()
if err != nil {
return err
}
// applicationRow 只转换规则编排所需的非敏感字段。
return service.EnsureAutomationRules(ctx, userID, row, result)
}
@@ -0,0 +1,23 @@
package server
// serverBatchManagementRuntime 将批次管理应用端口接到 Server 的 worker 生命周期边界。
type serverBatchManagementRuntime struct {
// server 保存批次 worker 启动与取消所需的 Server 生命周期入口。
server *Server
}
// StartBatch 启动已由应用服务声明租约的批量 worker。
func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) {
if runtime.server == nil {
return
}
runtime.server.startPublishBatchWorker(runtime.server.lifecycleContext(), userID, batchID, workerToken)
}
// CancelBatch 取消指定批次的后台 worker。
func (runtime serverBatchManagementRuntime) CancelBatch(batchID, workerToken string) {
if runtime.server == nil {
return
}
runtime.server.cancelPublishBatch(batchID, workerToken)
}
File diff suppressed because it is too large. Load diff
+69 -90
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
@@ -15,6 +14,7 @@ import (
"testing"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
@@ -131,6 +131,44 @@ func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffe
return &buf, mw.FormDataContentType()
}
// TestReadPublishImagesReturnsApplicationModel 验证 HTTP 图片解析只输出应用层图片模型。
func TestReadPublishImagesReturnsApplicationModel(t *testing.T) {
// body、contentType 保存带图片 multipart 请求体及其 MIME 类型。
body, contentType := buildPublishMultipart(t, nil)
// request 是待解析的商品发布 HTTP 请求。
request := httptest.NewRequest(http.MethodPost, "/items/publish", body)
request.Header.Set("Content-Type", contentType)
// parseErr 保存 multipart 解析错误。
parseErr := request.ParseMultipartForm(1 << 20)
if parseErr != nil {
t.Fatalf("解析 multipart 失败: %v", parseErr)
}
// images、readErr 保存图片解析结果及错误。
images, readErr := readPublishImages(request, 9)
if readErr != nil {
t.Fatalf("读取图片失败: %v", readErr)
}
if len(images) != 1 || images[0].Filename != "test.png" || images[0].ContentType != "image/png" || len(images[0].Data) == 0 {
t.Fatalf("图片应用模型异常: %+v", images)
}
// applicationImage 是显式检查返回值类型的应用层图片模型。
applicationImage := itemapp.Image(images[0])
if applicationImage.Filename != "test.png" {
t.Fatalf("图片未转换为应用模型: %+v", applicationImage)
}
}
// TestReadPublishImagesRejectsMissingMultipart 验证缺少图片时保持稳定输入错误。
func TestReadPublishImagesRejectsMissingMultipart(t *testing.T) {
// request 是没有 multipart 文件的商品发布请求。
request := httptest.NewRequest(http.MethodPost, "/items/publish", strings.NewReader(""))
// images、readErr 保存缺少图片时的解析结果及错误。
images, readErr := readPublishImages(request, 9)
if images != nil || readErr == nil || readErr.Error() != "至少上传 1 张商品图片" {
t.Fatalf("缺少图片错误异常: images=%v err=%v", images, readErr)
}
}
// TestPublishItemMissingCookieID 缺 cookie_id 应 400。
func TestPublishItemMissingCookieID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
@@ -632,93 +670,6 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
}
}
// TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency 验证商品多规格探测使用有界并发且覆盖全部候选商品。
func TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency(t *testing.T) {
// srv、store、cleanup 保存用于商品同步测试的服务、数据库和清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// stateMu 保护远端探测并发计数。
var stateMu sync.Mutex
// active、maxActive 保存当前及观测到的最大远端探测并发数。
active, maxActive := 0, 0
// probeCalls 统计测试客户端收到的商品详情探测请求数。
probeCalls := 0
// client 是带并发计数的商品详情测试客户端。
client := withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if !strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") {
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{}`)), Request: req}, nil
}
stateMu.Lock()
probeCalls++
active++
if active > maxActive {
maxActive = active
}
stateMu.Unlock()
time.Sleep(20 * time.Millisecond)
stateMu.Lock()
active--
stateMu.Unlock()
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"}]}}}`)), Request: req}, nil
}))
// items 保存等待探测的商品列表。
items := make([]mtop.ItemListItem, 8)
// index 表示当前商品在测试列表中的下标。
for index := range items {
items[index].ID = fmt.Sprintf("probe-%d", index)
}
// err 表示批量多规格探测错误。
err := srv.enrichSyncedItemMultiSpec(context.Background(), client, "unb=1; _m_h5_tk=t_1;", "acc1", items)
if err != nil {
t.Fatalf("enrich multi spec: %v", err)
}
if maxActive > itemSpecProbeConcurrency {
t.Fatalf("probe concurrency=%d want <=%d", maxActive, itemSpecProbeConcurrency)
}
// index、item 分别表示商品下标和当前探测结果。
for index, item := range items {
if !item.IsMultiSpec {
t.Fatalf("item %d was not marked multi spec", index)
}
}
// cachedItems 保存第二次调用使用的商品列表,验证命中跨请求缓存。
cachedItems := make([]mtop.ItemListItem, 8)
// index 表示缓存测试商品下标。
for index := range cachedItems {
cachedItems[index].ID = fmt.Sprintf("probe-%d", index)
}
// err 表示第二次商品多规格探测错误。
if err := srv.enrichSyncedItemMultiSpec(context.Background(), client, "unb=1; _m_h5_tk=t_1;", "acc1", cachedItems); err != nil {
t.Fatalf("cached enrich multi spec: %v", err)
}
if probeCalls != 8 {
t.Fatalf("cached probe calls=%d want 8", probeCalls)
}
// flags、err 保存数据库批量标记查询结果及错误,确认本地查询未误报候选商品。
flags, err := store.Items.MultiSpecFlags(context.Background(), "acc1", []string{"probe-0"})
if err != nil || len(flags) != 0 {
t.Fatalf("unexpected local flags=%v err=%v", flags, err)
}
}
// TestItemSpecCacheExpires 验证商品多规格缓存过期后不会继续返回旧值。
func TestItemSpecCacheExpires(t *testing.T) {
// srv 是仅用于验证商品多规格缓存生命周期的服务实例。
srv := &Server{itemSpecCache: map[string]itemSpecCacheEntry{
itemSpecCacheKey("acc1", "item-1"): {isMultiSpec: true, expiresAt: time.Now().Add(-time.Second)},
}}
// value、ok 保存过期缓存的读取结果。
value, ok := srv.cachedItemSpec("acc1", "item-1")
if ok || value {
t.Fatalf("expired cache should miss: value=%v ok=%v", value, ok)
}
srv.cacheItemSpec("acc1", "item-1", false)
value, ok = srv.cachedItemSpec("acc1", "item-1")
if !ok || value {
t.Fatalf("fresh false cache mismatch: value=%v ok=%v", value, ok)
}
}
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
func TestSyncItemsFromAccountFail(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
@@ -1000,6 +951,22 @@ func TestItemCRUD(t *testing.T) {
if rec4.Code != 200 {
t.Fatalf("multi-qty status=%d", rec4.Code)
}
// multiSpecBody 保存多规格开关请求,验证独立开关端点仍经商品写应用服务落库。
multiSpecBody := `{"is_multi_spec":false}`
// reqSpec 保存多规格开关请求。
reqSpec := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud/multi-spec", strings.NewReader(multiSpecBody))
reqSpec.AddCookie(cookie)
// recSpec 保存多规格开关响应。
recSpec := httptest.NewRecorder()
h.ServeHTTP(recSpec, reqSpec)
if recSpec.Code != http.StatusOK {
t.Fatalf("multi-spec status=%d body=%s", recSpec.Code, recSpec.Body.String())
}
// switched, switchErr 保存两个开关端点写入后的商品记录及读取错误。
switched, switchErr := store.Items.Get(ctx, "acc1", "it-crud")
if switchErr != nil || switched.IsMultiSpec || !switched.MultiQuantityDelivery {
t.Fatalf("开关更新未完整落库: item=%+v err=%v", switched, switchErr)
}
// 删除。
req5 := httptest.NewRequest(http.MethodDelete, "/items/acc1/it-crud", nil)
@@ -1010,6 +977,10 @@ func TestItemCRUD(t *testing.T) {
if rec5.Code != 200 {
t.Fatalf("delete status=%d", rec5.Code)
}
// deletedErr 保存删除后的详情读取结果,验证删除动作通过商品仓储的逻辑删除边界。
if _, deletedErr := store.Items.Get(ctx, "acc1", "it-crud"); deletedErr == nil {
t.Fatal("删除后的商品不应继续出现在商品详情查询中")
}
}
// TestListItemsFiltersByOwnedAccount 负责TestList商品列表FiltersByOwned账号相关处理。
@@ -1081,7 +1052,7 @@ func TestItemGetNotFound(t *testing.T) {
// TestCreateItem 新建商品。
func TestCreateItem(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
@@ -1089,7 +1060,7 @@ func TestCreateItem(t *testing.T) {
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00"}`
body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00","is_multi_qty_ship":true}`
// req 保存req,供当前处理流程使用
req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body))
req.AddCookie(cookie)
@@ -1099,6 +1070,14 @@ func TestCreateItem(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
// created、createErr 保存应用服务创建后的商品记录及读取错误。
created, createErr := store.Items.Get(context.Background(), "acc1", "new-item")
if createErr != nil {
t.Fatalf("读取新建商品失败: %v", createErr)
}
if created.ItemTitle != "新商品" || created.ItemPrice != "10.00" || !created.MultiQuantityDelivery {
t.Fatalf("创建字段或历史别名归一化异常: %+v", created)
}
}
// TestCreateItemMissingID 缺商品 ID 400。
File diff suppressed because it is too large. Load diff
-41
View File
@@ -8,8 +8,6 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
@@ -21,9 +19,7 @@ import (
"strings"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/netguard"
"xianyu-go/internal/xianyu/mtop"
)
// isPublicIP 保留给同包校验调用;实际策略统一由 netguard 维护。
@@ -112,43 +108,6 @@ func extractPublishImagesZip(raw []byte, dest string) error {
return nil
}
// loadBatchPublishImages 负责load批次发布Images相关处理。
func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) {
// refs 保存refs,供当前处理流程使用
var refs []string
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil {
return nil, fmt.Errorf("图片字段格式错误")
}
if len(refs) == 0 {
return nil, errors.New("至少上传 1 张商品图片")
}
// images 保存images,供当前处理流程使用
images := make([]mtop.PublishImage, 0, len(refs))
// ref 表示当前遍历过程中的ref
for _, ref := range refs {
// data 保存数据,供当前处理流程使用
var data []byte
// contentType 保存内容类型,供当前处理流程使用
var contentType string
// filename 保存filename,供当前处理流程使用
var filename string
// err 保存err,供当前处理流程使用
var err error
if isHTTPURL(ref) {
data, contentType, err = downloadImageURL(ctx, ref)
filename = pathBaseFromURL(ref)
} else {
data, contentType, filename, err = readBatchImageFile(uploadDir, ref)
}
if err != nil {
return nil, err
}
images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data})
}
return images, nil
}
// readBatchImageFile 负责read批次图片文件相关处理。
func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
// rel、err 保存rel、err,供当前处理流程使用
@@ -0,0 +1,14 @@
package server
import (
"context"
"xianyu-go/internal/adapter"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// loadBatchPublishImages 保留 Server 测试的历史调用形状,生产路径直接使用 adapter.LoadBatchPublishImages。
func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) {
return adapter.LoadBatchPublishImages(ctx, uploadDir, row.ImagesJSON, readBatchImageFile, downloadImageURL)
}
-257
View File
@@ -1,257 +0,0 @@
package server
import (
"context"
"xianyu-go/internal/db"
)
// itemPublishRepository 定义发布应用服务处理商品与批次状态所需的最小持久化能力。
type itemPublishRepository interface {
// LockCredentials 串行化账号凭证状态变更。
LockCredentials(cookieID string) func()
// LoadCookiePlatformDetail 读取平台发布所需的最小账号凭证视图。
LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error)
// UpdateCookieValueOwned 更新用户拥有账号的 Cookie。
UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error
// UpsertItem 写入发布成功后的商品基础信息。
UpsertItem(ctx context.Context, item *db.ItemInfoRow) error
// CreateBatch 创建批次及其明细行。
CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error
// RecountBatch 重算批次统计。
RecountBatch(ctx context.Context, batchID string) error
// GetBatch 查询用户拥有的批次。
GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error)
// ClaimBatch 抢占批次 worker 租约。
ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error)
// PendingRows 查询批次待处理明细。
PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error)
// FinalizeBatch 完成批次状态收口。
FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error)
// ListBatchesForUser 查询用户批次列表。
ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error)
// ListBatchRows 查询批次明细行。
ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error)
// RequestCancel 请求取消批次。
RequestCancel(ctx context.Context, batchID string) (string, bool, error)
// DeleteBatch 删除用户拥有的批次。
DeleteBatch(ctx context.Context, userID int64, batchID string) error
// ResetFailed 重置批次失败明细。
ResetFailed(ctx context.Context, batchID string) error
// RecoverableBatches 查询可恢复的批次。
RecoverableBatches(ctx context.Context, now int64, limit int) ([]db.ItemPublishBatch, error)
// FinalizeExpiredCancellation 收口已过期的取消请求。
FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error)
// ResetInterrupted 重置进程中断的批次。
ResetInterrupted(ctx context.Context, batchID string) error
// FailClaimedBatch 标记当前 worker 持有的批次失败。
FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error)
// RenewBatchLease 续租批次 worker。
RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error)
// ClaimRow 抢占批次明细行。
ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error)
// BatchStatus 查询批次状态。
BatchStatus(ctx context.Context, batchID string) (string, error)
// MarkClaimedRowFailed 标记 worker 持有的明细行失败。
MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error)
// FinalizeCanceled 收口已取消批次。
FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error)
// FinalizeInterrupted 收口被中断批次。
FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error)
// MarkClaimedRemoteStarted 记录远端发布已开始。
MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error)
// SaveClaimedRemoteResult 保存远端发布结果。
SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error)
// MarkClaimedRowSuccess 标记 worker 持有的明细行成功。
MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error)
// ClearUploadDir 清理批次上传目录记录。
ClearUploadDir(ctx context.Context, batchID string) error
// ExpiredUploads 查询过期上传目录。
ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]db.ItemPublishBatch, error)
// GetCookieValueOwned 读取用户拥有账号的 Cookie。
GetCookieValueOwned(ctx context.Context, userID int64, cookieID string) (string, error)
// ExistsOwned 判断账号是否归属于用户。
ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error)
}
// storeItemPublishRepository 将完整 Store 适配为发布应用服务窄 repository。
type storeItemPublishRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// LockCredentials 委托账号凭证锁。
func (r storeItemPublishRepository) LockCredentials(cookieID string) func() {
return r.store.LockAccountCredentials(cookieID)
}
// LoadCookiePlatformDetail 委托平台发布凭证查询并转换为 Server 内部模型。
func (r storeItemPublishRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) {
// data 和 err 保存平台运行视图查询结果。
data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if err != nil {
return nil, err
}
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}, nil
}
// UpdateCookieValueOwned 委托账号 Cookie 更新。
func (r storeItemPublishRepository) UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error {
return r.store.Cookies.UpdateValueOwned(ctx, cookieID, value, userID)
}
// UpsertItem 委托商品基础信息写入。
func (r storeItemPublishRepository) UpsertItem(ctx context.Context, item *db.ItemInfoRow) error {
return r.store.Items.Upsert(ctx, item)
}
// CreateBatch 委托批次创建。
func (r storeItemPublishRepository) CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error {
return r.store.PublishBatches.Create(ctx, batch, rows)
}
// RecountBatch 委托批次统计重算。
func (r storeItemPublishRepository) RecountBatch(ctx context.Context, batchID string) error {
return r.store.PublishBatches.Recount(ctx, batchID)
}
// GetBatch 委托用户批次查询。
func (r storeItemPublishRepository) GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error) {
return r.store.PublishBatches.Get(ctx, userID, batchID)
}
// ClaimBatch 委托批次租约抢占。
func (r storeItemPublishRepository) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
return r.store.PublishBatches.ClaimBatch(ctx, batchID, workerToken, leaseExpiresAt)
}
// PendingRows 委托批次待处理明细查询。
func (r storeItemPublishRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error) {
return r.store.PublishBatches.PendingRows(ctx, batchID, failedOnly)
}
// FinalizeBatch 委托批次完成状态收口。
func (r storeItemPublishRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
return r.store.PublishBatches.FinalizeBatch(ctx, batchID, workerToken)
}
// ListBatchesForUser 委托用户批次列表查询。
func (r storeItemPublishRepository) ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error) {
return r.store.PublishBatches.ListForUser(ctx, userID, limit)
}
// ListBatchRows 委托批次明细查询。
func (r storeItemPublishRepository) ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error) {
return r.store.PublishBatches.Rows(ctx, batchID)
}
// RequestCancel 委托批次取消请求。
func (r storeItemPublishRepository) RequestCancel(ctx context.Context, batchID string) (string, bool, error) {
return r.store.PublishBatches.RequestCancel(ctx, batchID)
}
// DeleteBatch 委托批次删除。
func (r storeItemPublishRepository) DeleteBatch(ctx context.Context, userID int64, batchID string) error {
return r.store.PublishBatches.Delete(ctx, userID, batchID)
}
// ResetFailed 委托失败明细重置。
func (r storeItemPublishRepository) ResetFailed(ctx context.Context, batchID string) error {
return r.store.PublishBatches.ResetFailed(ctx, batchID)
}
// RecoverableBatches 委托可恢复批次查询。
func (r storeItemPublishRepository) RecoverableBatches(ctx context.Context, now int64, limit int) ([]db.ItemPublishBatch, error) {
return r.store.PublishBatches.Recoverable(ctx, now, limit)
}
// FinalizeExpiredCancellation 委托过期取消收口。
func (r storeItemPublishRepository) FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) {
return r.store.PublishBatches.FinalizeExpiredCancellation(ctx, batchID, now)
}
// ResetInterrupted 委托中断批次重置。
func (r storeItemPublishRepository) ResetInterrupted(ctx context.Context, batchID string) error {
return r.store.PublishBatches.ResetInterrupted(ctx, batchID)
}
// FailClaimedBatch 委托 worker 持有批次失败标记。
func (r storeItemPublishRepository) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) {
return r.store.PublishBatches.FailClaimedBatch(ctx, batchID, workerToken)
}
// RenewBatchLease 委托批次租约续期。
func (r storeItemPublishRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
return r.store.PublishBatches.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt)
}
// ClaimRow 委托批次明细行抢占。
func (r storeItemPublishRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
return r.store.PublishBatches.ClaimRow(ctx, rowID, workerToken)
}
// BatchStatus 委托批次状态查询。
func (r storeItemPublishRepository) BatchStatus(ctx context.Context, batchID string) (string, error) {
return r.store.PublishBatches.BatchStatus(ctx, batchID)
}
// MarkClaimedRowFailed 委托 worker 持有明细行失败标记。
func (r storeItemPublishRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
return r.store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind)
}
// FinalizeCanceled 委托已取消批次收口。
func (r storeItemPublishRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) {
return r.store.PublishBatches.FinalizeCanceled(ctx, batchID, workerToken)
}
// FinalizeInterrupted 委托中断批次收口。
func (r storeItemPublishRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) {
return r.store.PublishBatches.FinalizeInterrupted(ctx, batchID, workerToken, message)
}
// MarkClaimedRemoteStarted 委托远端发布开始标记。
func (r storeItemPublishRepository) MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) {
return r.store.PublishBatches.MarkClaimedRemoteStarted(ctx, rowID, workerToken)
}
// SaveClaimedRemoteResult 委托远端发布结果保存。
func (r storeItemPublishRepository) SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
return r.store.PublishBatches.SaveClaimedRemoteResult(ctx, rowID, workerToken, itemID, itemURL, rawJSON)
}
// MarkClaimedRowSuccess 委托明细行成功标记。
func (r storeItemPublishRepository) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
return r.store.PublishBatches.MarkClaimedRowSuccess(ctx, rowID, workerToken, itemID, itemURL, rawJSON)
}
// ClearUploadDir 委托批次上传目录清理。
func (r storeItemPublishRepository) ClearUploadDir(ctx context.Context, batchID string) error {
return r.store.PublishBatches.ClearUploadDir(ctx, batchID)
}
// ExpiredUploads 委托过期上传目录查询。
func (r storeItemPublishRepository) ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]db.ItemPublishBatch, error) {
return r.store.PublishBatches.ExpiredUploads(ctx, cutoff, limit)
}
// GetCookieValueOwned 委托用户账号 Cookie 查询。
func (r storeItemPublishRepository) GetCookieValueOwned(ctx context.Context, userID int64, cookieID string) (string, error) {
return r.store.Cookies.GetValueOwned(ctx, userID, cookieID)
}
// ExistsOwned 委托账号归属查询。
func (r storeItemPublishRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
}
// newStoreItemPublishRepository 从完整 Store 构造发布应用服务窄 repository。
func newStoreItemPublishRepository(store *db.Store) itemPublishRepository {
if store == nil || store.Cookies == nil || store.Items == nil || store.PublishBatches == nil {
return nil
}
return storeItemPublishRepository{store: store}
}
// 确保 Store 适配器始终覆盖发布应用服务所需的全部能力。
var _ itemPublishRepository = storeItemPublishRepository{}
-431
View File
@@ -1,431 +0,0 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
var (
// errItemPublishBatchNotFound 表示当前用户无法访问指定批量任务。
errItemPublishBatchNotFound = errors.New("商品批量任务不存在")
// errItemPublishBatchConflict 表示批量任务的租约或状态发生并发冲突。
errItemPublishBatchConflict = errors.New("商品批量任务状态冲突")
// errItemPublishBatchInvalidState 表示批量任务当前状态不允许执行请求操作。
errItemPublishBatchInvalidState = errors.New("商品批量任务状态不允许执行该操作")
// errItemPublishBatchNoRows 表示批量任务没有可继续处理的明细行。
errItemPublishBatchNoRows = errors.New("商品批量任务没有可处理的明细行")
)
// itemPublishPreviewInput 是批量发布预检结果持久化所需的业务输入。
type itemPublishPreviewInput struct {
// UserID 是创建批次的用户标识。
UserID int64
// BatchID 是预检批次标识。
BatchID string
// DefaultCookieID 是未指定账号行使用的默认账号。
DefaultCookieID string
// Filename 是用户上传的表格文件名。
Filename string
// UploadDir 是批次图片和表格的受控目录。
UploadDir string
// Location 是批次统一发货地。
Location mtop.PublishLocation
// Rows 是解析并校验后的商品行。
Rows []publishBatchParsedRow
}
// itemPublishService 是商品发布应用服务,隔离 HTTP 适配与业务状态变更。
type itemPublishService struct {
// server 提供数据库、MTOP 客户端、运行时 Cookie 和 worker 生命周期依赖。
server *Server
// repository 提供商品发布用例所需的最小持久化能力。
repository itemPublishRepository
}
// itemPublishApplication 返回当前 Server 绑定的商品发布应用服务。
func (s *Server) itemPublishApplication() *itemPublishService {
return s.applicationServiceSet().itemPublish
}
// itemSinglePublishApplication 返回只负责单商品发布用例的应用服务。
func (s *Server) itemSinglePublishApplication() *itemapp.Service {
return s.applicationServiceSet().itemSinglePublish
}
// itemPublishRepositoryForServer 返回当前 Server 装配的发布持久化边界。
func (s *Server) itemPublishRepositoryForServer() itemPublishRepository {
return s.itemPublishApplication().repository
}
// RecommendCategory 调用平台类目推荐并持久化刷新后的账号登录状态。
func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (mtop.PublishCategory, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// recommender 和 ok 表示 MTOP 客户端是否支持类目推荐。
recommender, ok := s.mtopClient().(publishCategoryRecommender)
if !ok {
return mtop.PublishCategory{}, errors.New("当前 MTOP 客户端不支持类目推荐")
}
// unlock 释放当前账号的凭证串行化锁。
unlock := svc.repository.LockCredentials(cookieID)
// runtimeCookie 是需要在释放凭证锁后同步的刷新凭证。
runtimeCookie := ""
defer func() {
unlock()
if runtimeCookie != "" {
s.updateRunningCookie(context.Background(), cookieID, runtimeCookie)
}
}()
// err 和 latest 保存账号平台详情查询结果。
latest, err := s.loadCookiePlatformDetail(ctx, cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
return mtop.PublishCategory{}, errors.New("账号凭证已变化,请重试")
}
// requestCtx 和 cancel 控制类目推荐的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台上下文。
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
// category、updatedCookies 和 callErr 是平台推荐结果、刷新凭证及调用错误。
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, keyword)
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", persistErr)
}
if !handled && updatedCookies != "" && updatedCookies != latest.Value {
// err 表示保存平台返回新 Cookie 的错误。
if err := svc.repository.UpdateCookieValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", err)
}
runtimeCookie = updatedCookies
} else if handled && valueChanged {
runtimeCookie = value
}
if callErr != nil {
return mtop.PublishCategory{}, callErr
}
return category, nil
}
// PersistPreview 将预检行转换为数据库批次并返回兼容旧接口的预检 DTO。
func (svc *itemPublishService) PersistPreview(ctx context.Context, input itemPublishPreviewInput) (itemPublishBatchPreviewResponse, error) {
// rows 是待写入数据库的批量明细行。
rows := make([]db.ItemPublishBatchRow, 0, len(input.Rows))
// previewRows 是返回给前端的逐行预检视图。
previewRows := make([]publishBatchPreviewRow, 0, len(input.Rows))
// valid 和 invalid 记录预检通过与失败的行数。
valid, invalid := 0, 0
// parsed 是当前正在转换的预检行。
for _, parsed := range input.Rows {
// isValid 表示当前行是否没有校验错误。
isValid := len(parsed.Errors) == 0
if isValid {
valid++
} else {
invalid++
}
// imagesJSON、categoryJSON、automationJSON 和 rawJSON 是行数据的 JSON 表示。
imagesJSON, _ := json.Marshal(parsed.Images)
// categoryJSON 是商品类目的 JSON 表示。
categoryJSON, _ := json.Marshal(parsed.Category)
// automationJSON 是发布后自动化配置的 JSON 表示。
automationJSON, _ := json.Marshal(parsed.Automation)
// rawJSON 是原始导入行的 JSON 表示。
rawJSON, _ := json.Marshal(parsed.Raw)
// status、errorMessage 和 failureKind 保存数据库状态及失败分类。
status, errorMessage, failureKind := "pending", "", ""
if !isValid {
status, errorMessage, failureKind = "failed", strings.Join(parsed.Errors, ";"), "validation"
}
rows = append(rows, db.ItemPublishBatchRow{RowNo: parsed.RowNo, CookieID: parsed.CookieID, Title: parsed.Title, Description: parsed.Description, Price: parsed.Price, OriginalPrice: parsed.OriginalPrice, Quantity: parsed.Quantity, PostageMode: parsed.PostageMode, Postage: parsed.Postage, ImagesJSON: string(imagesJSON), CategoryJSON: string(categoryJSON), AutomationJSON: string(automationJSON), Status: status, ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON)})
previewRows = append(previewRows, publishBatchPreviewRow{RowNo: parsed.RowNo, Valid: isValid, Errors: parsed.Errors, CookieID: parsed.CookieID, Title: parsed.Title, Price: parsed.Price, Quantity: parsed.Quantity, Images: parsed.Images, Category: parsed.Category, Automation: parsed.Automation})
}
if len(rows) == 0 {
return itemPublishBatchPreviewResponse{}, errItemPublishBatchNoRows
}
// locationBytes 是批次发货地配置的 JSON 表示。
locationBytes, _ := json.Marshal(input.Location)
// err 表示批次及其明细的事务写入错误。
if err := svc.repository.CreateBatch(ctx, &db.ItemPublishBatch{ID: input.BatchID, UserID: input.UserID, DefaultCookieID: input.DefaultCookieID, Filename: input.Filename, UploadDir: input.UploadDir, LocationJSON: string(locationBytes), Status: "preview"}, rows); err != nil {
return itemPublishBatchPreviewResponse{}, fmt.Errorf("保存预检结果失败: %w", err)
}
_ = svc.repository.RecountBatch(ctx, input.BatchID)
return itemPublishBatchPreviewResponse{Success: true, PreviewID: input.BatchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows}, nil
}
// StartBatch 校验并声明批量任务租约,然后启动后台发布 worker。
func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// batch 和 err 保存批次查询结果。
batch, err := svc.repository.GetBatch(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() {
return "", errItemPublishBatchConflict
}
if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" && batch.Status != "running" {
return "", errItemPublishBatchInvalidState
}
// token 是本次 worker 租约的随机凭证。
token := randomHex(16)
// claimed 和 err 保存批次租约声明结果。
claimed, err := svc.repository.ClaimBatch(ctx, batch.ID, token, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
return "", fmt.Errorf("启动任务失败: %w", err)
}
if !claimed {
return "", errItemPublishBatchConflict
}
// pending 和 err 保存待处理明细查询结果。
pending, err := svc.repository.PendingRows(ctx, batch.ID, false)
if err != nil {
s.failClaimedPublishBatch(batch.ID, token)
return "", fmt.Errorf("读取任务失败: %w", err)
}
if len(pending) == 0 {
_, _, _ = svc.repository.FinalizeBatch(ctx, batch.ID, token)
return "", errItemPublishBatchNoRows
}
s.startPublishBatchWorker(s.lifecycleContext(), userID, batch.ID, token)
return batch.ID, nil
}
// ListBatches 查询用户的批量任务并映射为 HTTP 无关的响应 DTO。
func (svc *itemPublishService) ListBatches(ctx context.Context, userID int64, limit int) ([]itemPublishBatchResponse, error) {
// batches 和 err 保存用户批次列表查询结果。
batches, err := svc.repository.ListBatchesForUser(ctx, userID, limit)
if err != nil {
return nil, err
}
// result 是批次列表响应视图。
result := make([]itemPublishBatchResponse, 0, len(batches))
// i 是当前批次在查询结果中的索引。
for i := range batches {
result = append(result, publishBatchToMap(&batches[i], nil))
}
return result, nil
}
// GetBatch 查询用户拥有的批量任务及其明细行。
func (svc *itemPublishService) GetBatch(ctx context.Context, userID int64, batchID string) (itemPublishBatchResponse, error) {
// batch 和 err 保存批次查询结果。
batch, err := svc.repository.GetBatch(ctx, userID, batchID)
if err != nil {
return itemPublishBatchResponse{}, errItemPublishBatchNotFound
}
// rows 和 err 保存批次明细查询结果。
rows, err := svc.repository.ListBatchRows(ctx, batch.ID)
if err != nil {
return itemPublishBatchResponse{}, err
}
return publishBatchToMap(batch, rows), nil
}
// CancelBatch 请求批量任务取消并通知内存中的 worker。
func (svc *itemPublishService) CancelBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// err 表示批次所有权查询错误。
if _, err := svc.repository.GetBatch(ctx, userID, batchID); err != nil {
return "", errItemPublishBatchNotFound
}
// token、running 和 err 保存取消请求及当前 worker 状态。
token, running, err := svc.repository.RequestCancel(ctx, batchID)
if err != nil {
if errors.Is(err, db.ErrPublishBatchChanged) {
return "", errItemPublishBatchConflict
}
return "", err
}
if running {
s.cancelPublishBatch(batchID, token)
}
if running {
return "canceling", nil
}
return "canceled", nil
}
// DeleteBatch 删除非运行中的批量任务并返回其上传目录供适配层清理。
func (svc *itemPublishService) DeleteBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// batch 和 err 保存批次查询结果。
batch, err := svc.repository.GetBatch(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" || batch.Status == "canceling" {
return "", errItemPublishBatchConflict
}
// err 表示批次删除错误。
if err := svc.repository.DeleteBatch(ctx, userID, batchID); err != nil {
return "", err
}
return batch.UploadDir, nil
}
// RetryFailedBatch 重置失败明细并启动仅处理失败项的后台 worker。
func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// batch 和 err 保存批次查询结果。
batch, err := svc.repository.GetBatch(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() {
return "", errItemPublishBatchConflict
}
// token 是本次重试 worker 的租约凭证。
token := randomHex(16)
// claimed 和 err 保存重试租约声明结果。
claimed, err := svc.repository.ClaimBatch(ctx, batchID, token, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
return "", err
}
if !claimed {
return "", errItemPublishBatchConflict
}
// err 表示重置失败明细的错误。
if err := svc.repository.ResetFailed(ctx, batchID); err != nil {
s.failClaimedPublishBatch(batchID, token)
return "", err
}
_ = svc.repository.RecountBatch(ctx, batchID)
// pending 和 err 保存可重试明细查询结果。
pending, err := svc.repository.PendingRows(ctx, batchID, false)
if err != nil {
s.failClaimedPublishBatch(batchID, token)
return "", err
}
if len(pending) == 0 {
_, _, _ = svc.repository.FinalizeBatch(ctx, batchID, token)
return "", errItemPublishBatchNoRows
}
s.startPublishBatchWorker(s.lifecycleContext(), userID, batchID, token)
return batchID, nil
}
// serverItemPublishPort 将 MTOP、Cookie 会话与运行时同步适配为应用商品发布端口。
type serverItemPublishPort struct {
// server 保存平台调用和账号凭证适配所需的 Server 依赖。
server *Server
// repository 提供账号锁、平台凭证查询和 Cookie 写回能力。
repository itemPublishRepository
}
// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。
func (p serverItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) {
// unlock 释放当前账号的凭证串行化锁;锁覆盖现有平台会话不变量。
unlock := p.repository.LockCredentials(input.CookieID)
// latest 保存加锁后读取的平台运行凭证视图。
latest, err := p.server.loadCookiePlatformDetail(ctx, input.CookieID)
if err != nil || latest == nil || latest.UserID != input.UserID || !hasStoredCookieCredential(latest) {
unlock()
return itemapp.PublishOutcome{}, errors.New("账号凭证已变化,请重试")
}
// requestCtx 和 cancel 控制单商品平台发布的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
// images 保存应用图片 DTO 转换后的平台图片请求。
images := make([]mtop.PublishImage, 0, len(input.Images))
// image 表示当前待转换的应用图片。
for _, image := range input.Images {
images = append(images, mtop.PublishImage{Filename: image.Filename, ContentType: image.ContentType, Data: image.Data})
}
// location 保存应用发货地 DTO 转换后的平台位置请求。
var location *mtop.PublishLocation
if input.Location != nil {
location = &mtop.PublishLocation{
Area: input.Location.Area, City: input.Location.City, DivisionID: input.Location.DivisionID,
Longitude: input.Location.Longitude, Latitude: input.Location.Latitude, POIID: input.Location.POIID,
POIName: input.Location.POIName, Province: input.Location.Province,
}
}
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台调用上下文。
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
// result 和 callErr 保存平台发布结果及调用错误。
result, callErr := p.server.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{
Title: input.Title, Description: input.Description, PriceCents: input.PriceCents,
OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity,
PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true,
Location: location, Images: images,
})
// runtimeCookie 保存需要在释放凭证锁后同步到运行时的刷新 Cookie。
runtimeCookie := ""
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
value, valueChanged, handled, persistErr := p.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
if p.server.Logger != nil {
p.server.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr)
}
} else if handled && valueChanged {
runtimeCookie = value
} else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value {
// saveErr 表示保存平台返回新 Cookie 的错误。
if saveErr := p.repository.UpdateCookieValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil {
persistErr = saveErr
} else {
runtimeCookie = result.UpdatedCookies
}
}
unlock()
if runtimeCookie != "" {
p.server.updateRunningCookie(ctx, input.CookieID, runtimeCookie)
}
if callErr != nil {
if persistErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
}
p.server.recoverExpiredMTOPSession(ctx, input.CookieID, callErr)
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr
}
if result == nil || strings.TrimSpace(result.ItemID) == "" {
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, nil
}
return itemapp.PublishOutcome{Result: &itemapp.PublishResult{
ItemID: result.ItemID, ItemURL: result.ItemURL, Title: result.Title, PriceText: result.PriceText,
CategoryID: result.CategoryID, CategoryName: result.CategoryName, ImageURL: result.ImageURL,
Quantity: result.Quantity, RawData: result.RawData,
}, ResponseCookieErr: persistErr}, nil
}
// storeItemPublishItemRepository 将商品数据库写入适配为应用层商品仓储端口。
type storeItemPublishItemRepository struct {
// store 保存数据库聚合入口,仅在 Server 适配器内部使用。
store *db.Store
}
// Upsert 保存应用层商品记录,并在边界转换为数据库行模型。
func (r storeItemPublishItemRepository) Upsert(ctx context.Context, record itemapp.ItemRecord) error {
return r.store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: record.CookieID, ItemID: record.ItemID, ItemTitle: record.ItemTitle,
ItemDescription: record.ItemDescription, ItemCategory: record.ItemCategory,
ItemPrice: record.ItemPrice, ItemDetail: record.ItemDetail,
MultiQuantityDelivery: record.MultiQuantityDelivery,
})
}
// newItemPublishApplication 创建单商品发布应用服务并绑定 Server 适配器。
func newItemPublishApplication(server *Server) *itemapp.Service {
// publisher 是商品发布平台端口适配器。
publisher := serverItemPublishPort{server: server, repository: newStoreItemPublishRepository(server.Store)}
// repository 是商品本地持久化端口适配器。
repository := storeItemPublishItemRepository{store: server.Store}
// service 和 err 保存应用服务构造结果。
service, err := itemapp.NewService(publisher, repository)
if err != nil {
panic(fmt.Sprintf("商品发布应用服务装配失败: %v", err))
}
return service
}
+21 -21
View File
@@ -4,26 +4,26 @@ import (
"context"
"testing"
"xianyu-go/internal/xianyu/mtop"
itemapp "xianyu-go/internal/application/items"
)
// TestItemPublishServicePersistPreview 验证预检结果由应用服务统一持久化并可再次读取。
func TestItemPublishServicePersistPreview(t *testing.T) {
// TestBatchManagementReadsPersistedPreview 验证批次管理应用服务可以读取预检持久化结果。
func TestBatchManagementReadsPersistedPreview(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// service 是待验证的商品发布应用服务。
service := srv.itemPublishApplication()
// service 是待验证的预检持久化应用服务。
service := srv.itemBatchPreviewPersistenceApplication()
// preview 和 err 保存预检持久化结果。
preview, err := service.PersistPreview(context.Background(), itemPublishPreviewInput{
UserID: 1, BatchID: "batch_service_test", DefaultCookieID: "acc1",
preview, err := service.Persist(context.Background(), itemapp.BatchPreviewPersistenceBatch{
UserID: 1, ID: "batch_service_test", DefaultCookieID: "acc1",
Filename: "products.csv", UploadDir: "/tmp/publish-service-test",
Location: mtop.PublishLocation{DivisionID: "3301"},
Rows: []publishBatchParsedRow{{
RowNo: 2, CookieID: "acc1", Title: "服务层商品", Price: "12.50", Quantity: 1,
Images: []string{"img/a.png"}, Category: mtop.PublishCategory{CatID: "5001", CatName: "虚拟商品"},
}},
})
Location: itemapp.Location{DivisionID: "3301"},
}, []itemapp.BatchPreviewRow{{
RowNo: 2, CookieID: "acc1", Title: "服务层商品", Price: "12.50", Quantity: 1,
Images: []string{"img/a.png"}, Category: itemapp.BatchPreviewCategory{CatID: "5001", CatName: "虚拟商品"},
}},
)
if err != nil {
t.Fatalf("PersistPreview error: %v", err)
}
@@ -31,23 +31,23 @@ func TestItemPublishServicePersistPreview(t *testing.T) {
t.Fatalf("unexpected preview: %+v", preview)
}
// got 和 err 保存从数据库读取的批次视图。
got, err := service.GetBatch(context.Background(), 1, preview.PreviewID)
details, err := srv.itemBatchManagementApplication().GetBatch(context.Background(), 1, preview.PreviewID)
if err != nil {
t.Fatalf("GetBatch error: %v", err)
}
if got.ID != preview.PreviewID || len(got.Rows) != 1 || got.Rows[0].Title != "服务层商品" {
t.Fatalf("unexpected batch: %+v", got)
if details.Batch.ID != preview.PreviewID || len(details.Rows) != 1 || details.Rows[0].Title != "服务层商品" {
t.Fatalf("unexpected batch: %+v", details)
}
}
// TestItemPublishServiceStartBatchNotFound 验证应用服务对越权或不存在批次返回统一领域错误。
func TestItemPublishServiceStartBatchNotFound(t *testing.T) {
// TestBatchManagementStartBatchNotFound 验证批次管理服务对越权或不存在批次返回统一领域错误。
func TestBatchManagementStartBatchNotFound(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// err 保存不存在批次的业务错误。
_, err := srv.itemPublishApplication().StartBatch(context.Background(), 1, "missing-batch")
if err != errItemPublishBatchNotFound {
t.Fatalf("error=%v want %v", err, errItemPublishBatchNotFound)
_, err := srv.itemBatchManagementApplication().StartBatch(context.Background(), 1, "missing-batch", publishBatchLease)
if err != itemapp.ErrBatchNotFound {
t.Fatalf("error=%v want %v", err, itemapp.ErrBatchNotFound)
}
}
@@ -0,0 +1,59 @@
package server
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
itemapp "xianyu-go/internal/application/items"
)
// itemSyncRepositoryStub 是隔离 HTTP 错误映射测试的商品同步 Port 桩。
type itemSyncRepositoryStub struct {
// owned 表示桩返回的账号归属结果。
owned bool
// allErr 保存全量同步桩返回的错误。
allErr error
}
// OwnsAccount 返回预设的账号归属结果。
func (s *itemSyncRepositoryStub) OwnsAccount(_ context.Context, _ int64, _ string) (bool, error) {
return s.owned, nil
}
// SyncAll 返回预设的全量同步错误。
func (s *itemSyncRepositoryStub) SyncAll(_ context.Context, _ itemapp.SyncQuery) (itemapp.SyncAllResult, error) {
return itemapp.SyncAllResult{}, s.allErr
}
// SyncPage 返回无错误的空分页结果,满足同步 Port 的完整契约。
func (s *itemSyncRepositoryStub) SyncPage(_ context.Context, _ itemapp.SyncQuery) (itemapp.SyncPageResult, error) {
return itemapp.SyncPageResult{}, nil
}
// TestSyncItemsPersistenceFailureMapsToServerError 验证本地持久化失败不会伪装成平台错误。
func TestSyncItemsPersistenceFailureMapsToServerError(t *testing.T) {
// srv、cleanup 保存本次 HTTP 测试使用的服务和清理函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// persistenceErr 表示应用 Port 报告的本地写入失败。
persistenceErr := &itemapp.SyncError{Kind: itemapp.SyncErrorPersistence, Err: errors.New("写入失败")}
// srv.applications.itemSync 替换为可控的应用服务,隔离数据库故障映射。
srv.applications.itemSync = itemapp.NewSyncService(&itemSyncRepositoryStub{owned: true, allErr: persistenceErr})
// h 保存当前服务路由。
h := srv.Router()
// cookie 保存认证成功后的会话 Cookie。
cookie := loginHelper(t, h)
// req 保存发起商品全集同步的请求。
req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1"}`))
req.AddCookie(cookie)
// rec 保存 HTTP 响应。
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
}
+286 -273
View File
@@ -4,15 +4,72 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/application/keywords"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountKeywordsReal 关键字端点。
// keywordRequest 是普通关键词接口使用的文字回复请求 DTO。
type keywordRequest struct {
// Keyword 是触发匹配文本。
Keyword string `json:"keyword"`
// Reply 是文字回复正文。
Reply string `json:"reply"`
}
// keywordBatchItem 是带商品范围的关键词批量项 DTO。
type keywordBatchItem struct {
// Keyword 是触发匹配文本。
Keyword string `json:"keyword"`
// Reply 是文字回复正文。
Reply string `json:"reply"`
// ItemID 是可选商品标识。
ItemID string `json:"item_id"`
// Type 是 text 或 image 回复类型。
Type string `json:"type"`
// ImageURL 是图片回复地址。
ImageURL string `json:"image_url"`
}
// keywordBatchRequest 是关键词批量替换或单项创建请求 DTO。
type keywordBatchRequest struct {
// Keyword 是单项创建的触发匹配文本。
Keyword string `json:"keyword"`
// Reply 是单项创建的文字回复正文。
Reply string `json:"reply"`
// ItemID 是单项创建的可选商品标识。
ItemID string `json:"item_id"`
// Type 是单项创建的回复类型。
Type string `json:"type"`
// ImageURL 是单项创建的图片回复地址。
ImageURL string `json:"image_url"`
// Keywords 是批量替换项;为空指针表示请求使用单项模式。
Keywords *[]keywordBatchItem `json:"keywords"`
}
// keywordUpdateRequest 是按 ID 更新关键词的请求 DTO。
type keywordUpdateRequest struct {
// Keyword 是触发匹配文本。
Keyword string `json:"keyword"`
// Reply 是文字回复正文。
Reply string `json:"reply"`
// ItemID 是可选商品标识。
ItemID string `json:"item_id"`
// Type 是 text 或 image 回复类型。
Type string `json:"type"`
// ImageURL 是图片回复地址。
ImageURL string `json:"image_url"`
}
// itemReplyRequest 是指定商品回复写入请求 DTO。
type itemReplyRequest struct {
// ReplyContent 是商品命中后的回复正文。
ReplyContent string `json:"reply_content"`
}
// mountKeywordsReal 注册关键词回复兼容路由。
func (s *Server) mountKeywordsReal(r chi.Router) {
r.Get("/keywords/{cid}", s.listKeywords)
r.Post("/keywords/{cid}", s.addKeyword)
@@ -24,313 +81,260 @@ func (s *Server) mountKeywordsReal(r chi.Router) {
r.Delete("/keywords/{cid}/{index}", s.deleteKeyword)
}
// listKeywords 负责listKeywords相关处理。
// keywordApplication 返回关键词回复应用服务;具体依赖由 Server 统一装配。
func (s *Server) keywordApplication() *keywords.Service {
return s.applicationServiceSet().keywords
}
// keywordUserID 从认证上下文读取当前用户,不读取任何账号凭证。
func keywordUserID(w http.ResponseWriter, r *http.Request) (int64, bool) {
// session 是认证中间件注入的当前用户会话。
session := auth.SessionFromContext(r.Context())
if session == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return 0, false
}
return session.UserID, true
}
// writeKeywordError 将应用层错误映射为现有关键词接口的 HTTP 语义。
func writeKeywordError(w http.ResponseWriter, err error, fallback string) {
if err == nil {
return
}
// validationErr 是可安全展示给调用方的参数校验提示。
var validationErr *keywords.ValidationError
if errors.As(err, &validationErr) {
writeErr(w, http.StatusBadRequest, validationErr.Error())
return
}
switch {
case errors.Is(err, keywords.ErrForbidden):
writeErr(w, http.StatusForbidden, "无权限操作该账号")
case errors.Is(err, keywords.ErrNotFound):
writeErr(w, http.StatusNotFound, "关键字不存在")
case errors.Is(err, keywords.ErrInvalidInput):
writeErr(w, http.StatusBadRequest, "请求参数无效")
default:
writeErr(w, http.StatusInternalServerError, fallback)
}
}
// listKeywords 返回兼容的基础关键词响应。
func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
// rows 保存应用层查询结果。
rows, err := s.keywordApplication().List(r.Context(), userID, cookieID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
writeKeywordError(w, err, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordBasicResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordBasicResponse{Keyword: k.Keyword, Reply: k.Reply})
// result 保存 HTTP 基础响应,隐藏数据库模型和内部字段。
result := make([]keywordBasicResponse, 0, len(rows))
// row 是当前待映射的关键词规则。
for _, row := range rows {
result = append(result, keywordBasicResponse{Keyword: row.Keyword, Reply: row.Reply})
}
writeJSON(w, http.StatusOK, out)
writeJSON(w, http.StatusOK, result)
}
// listKeywordsWithItemID 负责listKeywordsWith商品ID相关处理。
// listKeywordsWithItemID 返回带商品范围的兼容关键词响应。
func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
// rows 保存应用层查询结果。
rows, err := s.keywordApplication().List(r.Context(), userID, cookieID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
writeKeywordError(w, err, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordItemResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordItemResponse{Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID})
// result 保存带商品字段的 HTTP 响应。
result := make([]keywordItemResponse, 0, len(rows))
// row 是当前待映射的关键词规则。
for _, row := range rows {
result = append(result, keywordItemResponse{Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID})
}
writeJSON(w, http.StatusOK, out)
writeJSON(w, http.StatusOK, result)
}
// listKeywordsWithType 负责listKeywordsWith类型相关处理。
// listKeywordsWithType 返回支持 text/image 类型的兼容响应。
func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
// rows 保存应用层查询结果。
rows, err := s.keywordApplication().List(r.Context(), userID, cookieID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
writeKeywordError(w, err, "查询失败")
return
}
// out 保存out,供当前处理流程使用
out := make([]keywordTypedResponse, 0, len(rows))
// k 表示当前遍历过程中的k
for _, k := range rows {
out = append(out, keywordTypedResponse{
ID: k.ID, Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID,
Type: k.Type, ImageURL: k.ImageURL,
})
// result 保存带类型字段的 HTTP 响应。
result := make([]keywordTypedResponse, 0, len(rows))
// row 是当前待映射的关键词规则。
for _, row := range rows {
result = append(result, keywordTypedResponse{ID: row.ID, Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID, Type: row.Type, ImageURL: row.ImageURL})
}
writeJSON(w, http.StatusOK, out)
writeJSON(w, http.StatusOK, result)
}
// addKeyword 负责add关键词相关处理。
// addKeyword 创建一条普通文字关键词规则。
func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
// request 是普通关键词请求 DTO。
var request keywordRequest
// err 表示请求 JSON 解码失败。
if err := decodeJSON(r, &request); err != nil {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
if strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
if // err 保存err,供当前处理流程使用
_, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
// _, err 表示创建操作的结果;ID 对兼容响应不向客户端暴露。
if _, err := s.keywordApplication().Add(r.Context(), userID, cookieID, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, Type: "text"}); err != nil {
writeKeywordError(w, err, "添加失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// addKeywordWithItemID 负责add关键词With商品ID相关处理。
// addKeywordWithItemID 创建或批量替换带商品范围的关键词规则。
func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
Keywords *[]struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
} `json:"keywords"`
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
// request 是单项或批量关键词请求 DTO。
var request keywordBatchRequest
// err 表示请求 JSON 解码失败。
if err := decodeJSON(r, &request); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.Keywords != nil {
// rows 保存rows,供当前处理流程使用
rows := make([]db.KeywordRow, 0, len(*req.Keywords))
// item 表示当前遍历过程中的商品
for _, item := range *req.Keywords {
if strings.TrimSpace(item.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
item.Type = strings.ToLower(strings.TrimSpace(item.Type))
if item.Type == "" {
item.Type = "text"
}
switch item.Type {
case "text":
if strings.TrimSpace(item.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
item.ImageURL = ""
case "image":
if strings.TrimSpace(item.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
item.Reply = ""
default:
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
rows = append(rows, db.KeywordRow{
CookieID: cid,
Keyword: item.Keyword,
Reply: item.Reply,
ItemID: item.ItemID,
Type: item.Type,
ImageURL: item.ImageURL,
})
if request.Keywords != nil {
// drafts 保存经过应用服务校验的批量关键词输入。
drafts := make([]keywords.Draft, 0, len(*request.Keywords))
// item 是当前待转换的批量请求项。
for _, item := range *request.Keywords {
drafts = append(drafts, keywords.Draft{Keyword: item.Keyword, Reply: item.Reply, ItemID: item.ItemID, Type: item.Type, ImageURL: item.ImageURL})
}
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
// err 表示批量替换规则的应用服务错误。
if err := s.keywordApplication().Replace(r.Context(), userID, cookieID, drafts); err != nil {
writeKeywordError(w, err, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
return
}
if strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if req.Type == "" {
req.Type = "text"
}
if req.Type == "text" && strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
if req.Type == "image" && strings.TrimSpace(req.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
if req.Type != "text" && req.Type != "image" {
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
if req.Type == "image" {
req.Reply = ""
} else {
req.ImageURL = ""
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, req.ItemID, req.Type, req.ImageURL)
// id 是新建规则的持久化标识;兼容响应保留该字段。
id, err := s.keywordApplication().Add(r.Context(), userID, cookieID, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, ItemID: request.ItemID, Type: request.Type, ImageURL: request.ImageURL})
if err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
writeKeywordError(w, err, "添加失败")
return
}
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateKeywordByID 负责update关键词ByID相关处理。
// updateKeywordByID 按关键词 ID 更新 text/image 规则。
func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
// id 是路由中的关键词持久化标识。
id, parseErr := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if parseErr != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
// request 是关键词更新请求 DTO。
var request keywordUpdateRequest
// err 表示请求 JSON 解码失败。
if err := decodeJSON(r, &request); err != nil {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if req.Type == "" {
req.Type = "text"
}
switch req.Type {
case "text":
if strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
req.ImageURL = ""
case "image":
if strings.TrimSpace(req.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
req.Reply = ""
default:
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
err = s.Store.Keywords.UpdateByID(r.Context(), db.KeywordRow{
ID: id, CookieID: cid, Keyword: req.Keyword, Reply: req.Reply,
ItemID: req.ItemID, Type: req.Type, ImageURL: req.ImageURL,
})
if err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
writeErr(w, http.StatusInternalServerError, "保存失败")
// updateErr 表示应用层更新结果。
updateErr := s.keywordApplication().Update(r.Context(), userID, cookieID, id, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, ItemID: request.ItemID, Type: request.Type, ImageURL: request.ImageURL})
if updateErr != nil {
writeKeywordError(w, updateErr, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteKeywordByID 负责delete关键词ByID相关处理。
// deleteKeywordByID 按持久化 ID 删除关键词规则。
func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
// id 是路由中的关键词持久化标识。
id, parseErr := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if parseErr != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.DeleteByID(r.Context(), cid, id); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
// deleteErr 表示应用层删除结果。
deleteErr := s.keywordApplication().DeleteByID(r.Context(), userID, cookieID, id)
if deleteErr != nil {
writeKeywordError(w, deleteErr, "关键字不存在")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteKeyword 负责delete关键词相关处理。
// deleteKeyword 按兼容的零基索引删除关键词规则。
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cid")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// index 保存index,供当前处理流程使用
index := atoiDefault(chi.URLParam(r, "index"), -1)
if // err 保存err,供当前处理流程使用
err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
// index 是按关键词 ID 顺序解释的零基索引。
index, parseErr := strconv.Atoi(chi.URLParam(r, "index"))
if parseErr != nil {
index = -1
}
// deleteErr 表示应用层删除结果。
deleteErr := s.keywordApplication().DeleteByIndex(r.Context(), userID, cookieID, index)
if deleteErr != nil {
writeKeywordError(w, deleteErr, "关键字不存在")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// ---- 指定商品回复 ----
// mountItemRepliesReal 注册指定商品回复兼容路由。
func (s *Server) mountItemRepliesReal(r chi.Router) {
r.Get("/itemReplays", s.listItemReplies)
r.Get("/item-reply/{cookie_id}/{item_id}", s.getItemReply)
@@ -338,84 +342,93 @@ func (s *Server) mountItemRepliesReal(r chi.Router) {
r.Delete("/item-reply/{cookie_id}/{item_id}", s.deleteItemReply)
}
// listItemReplies 负责list商品回复列表相关处理。
// listItemReplies 返回当前用户全部账号的指定商品回复。
func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
cookieIDs, _ := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 是当前用户拥有的账号 ID。
var result []itemReplyResponse
// cid 表示当前遍历过程中的cid
for _, cid := range cookieIDs {
// rows 保存rows,供当前处理流程使用
rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid)
// ir 表示当前遍历过程中的ir
for _, ir := range rows {
result = append(result, itemReplyResponse{
ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent,
})
}
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// rows 保存应用层商品回复结果。
rows, err := s.keywordApplication().ListItemReplies(r.Context(), userID)
if err != nil {
// 兼容历史接口:列表查询失败仍返回空列表和 200。
writeJSON(w, http.StatusOK, []itemReplyResponse{})
return
}
// result 保存 HTTP 商品回复响应。
result := make([]itemReplyResponse, 0, len(rows))
// row 是当前待映射的商品回复。
for _, row := range rows {
result = append(result, itemReplyResponse{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent})
}
writeJSON(w, http.StatusOK, result)
}
// getItemReply 负责get商品回复相关处理。
// getItemReply 返回指定商品回复;缺失时保持历史空正文响应。
func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cookie_id")
// itemID 是路由中的商品标识。
itemID := chi.URLParam(r, "item_id")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
// ir、err 保存ir、err,供当前处理流程使用
ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID)
if err != nil {
// row 保存应用层商品回复结果。
row, err := s.keywordApplication().GetItemReply(r.Context(), userID, cookieID, itemID)
if errors.Is(err, keywords.ErrNotFound) {
writeJSON(w, http.StatusOK, itemReplyResponse{ReplyContent: ""})
return
}
writeJSON(w, http.StatusOK, itemReplyResponse{
ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent,
})
}
// setItemReply 负责set商品回复相关处理。
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
if err != nil {
writeKeywordError(w, err, "查询失败")
return
}
// itemID 保存商品ID,供当前处理流程使用
writeJSON(w, http.StatusOK, itemReplyResponse{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent})
}
// setItemReply 覆盖指定商品回复。
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cookie_id")
// itemID 是路由中的商品标识。
itemID := chi.URLParam(r, "item_id")
// req 保存req,供当前处理流程使用
var req struct {
ReplyContent string `json:"reply_content"`
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
// request 是指定商品回复请求 DTO。
var request itemReplyRequest
// err 表示请求 JSON 解码失败。
if err := decodeJSON(r, &request); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
// err 表示应用层写入结果。
if err := s.keywordApplication().SetItemReply(r.Context(), userID, cookieID, itemID, request.ReplyContent); err != nil {
writeKeywordError(w, err, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteItemReply 负责delete商品回复相关处理。
// deleteItemReply 删除指定商品回复。
func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
// cookieID 是路由中的账号标识。
cookieID := chi.URLParam(r, "cookie_id")
// itemID 是路由中的商品标识。
itemID := chi.URLParam(r, "item_id")
// userID 是当前认证用户标识。
userID, ok := keywordUserID(w, r)
if !ok {
return
}
// itemID 保存商品ID,供当前处理流程使用
itemID := chi.URLParam(r, "item_id")
if // err 保存err,供当前处理流程使用
err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
// err 表示应用层删除结果。
if err := s.keywordApplication().DeleteItemReply(r.Context(), userID, cookieID, itemID); err != nil {
writeKeywordError(w, err, "删除失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
+19 -86
View File
@@ -2,102 +2,35 @@ package server
import (
"context"
"strings"
"time"
"xianyu-go/internal/db"
accountapp "xianyu-go/internal/application/account"
)
// loginMethodManual 保存登录方法Manual,供当前处理流程使用
const (
loginMethodManual = "manual"
loginMethodPassword = "password"
loginMethodQRScan = "qr_scan"
loginStatusSuccess = "success"
loginStatusFailed = "failed"
// loginMethodPassword 保留 Server 内部调用方使用的账号密码登录方式别名。
loginMethodPassword = accountapp.LoginMethodPassword
// loginMethodQRScan 保留 Server 内部调用方使用的扫码登录方式别名。
loginMethodQRScan = accountapp.LoginMethodQRScan
)
// normalizeLoginMethod 负责normalize登录方法相关处理。
func normalizeLoginMethod(method string) string {
switch strings.ToLower(strings.TrimSpace(method)) {
case "manual", "cookie", "manual_cookie":
return loginMethodManual
case "password", "password_login":
return loginMethodPassword
case "qr", "qr_login", "qr_scan":
return loginMethodQRScan
default:
return strings.ToLower(strings.TrimSpace(method))
}
}
// markSuccessfulLogin 负责markSuccessful登录相关处理。
// markSuccessfulLogin 将 Server 登录成功事件交给账号应用服务审计,不在 HTTP 层组装数据库模型。
func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) {
// repository 提供登录审计和账号状态持久化能力。
repository := s.accountLoginRepositoryForServer()
if repository == nil {
if s == nil {
return
}
method = normalizeLoginMethod(method)
if method == "" {
// auditService 保存应用层登录审计服务;它拥有归一化、启用和日志写入编排。
auditService := s.loginAuditApplication()
if auditService == nil {
return
}
// at 保存at,供当前处理流程使用
at := time.Now().Unix()
if // err 保存err,供当前处理流程使用
err := repository.MarkLogin(ctx, cookieID, method, at); err != nil {
if s.Logger != nil {
s.Logger.Warn("记录账号登录方式失败", "cookie_id", cookieID, "method", method, "err", err)
}
return
}
if method == loginMethodPassword || method == loginMethodQRScan {
if // err 保存err,供当前处理流程使用
err := repository.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil {
s.Logger.Warn("成功登录后启用账号失败", "cookie_id", cookieID, "method", method, "err", err)
}
}
s.addLoginLog(ctx, cookieID, userID, method, loginStatusSuccess, "", message, at)
}
// addLoginLog 负责add登录Log相关处理。
func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64, method, status, failureReason, message string, at int64) {
// repository 提供登录日志持久化能力。
repository := s.accountLoginRepositoryForServer()
if repository == nil {
return
}
if at == 0 {
at = time.Now().Unix()
}
if // err 保存err,供当前处理流程使用
err := repository.AddLoginLog(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
OwnerID: userID,
AccountIdentifier: cookieID,
Method: normalizeLoginMethod(method),
Status: status,
Message: truncate(message, 500),
TriggerReason: loginTriggerReason(method),
FailureReason: failureReason,
ErrorMessage: truncate(message, 500),
CreatedAt: at,
}); err != nil && s.Logger != nil {
s.Logger.Warn("记录账号登录日志失败", "cookie_id", cookieID, "method", method, "status", status, "err", err)
}
}
// loginTriggerReason 负责登录Trigger原因相关处理。
func loginTriggerReason(method string) string {
switch normalizeLoginMethod(method) {
case loginMethodManual:
return "手动Cookie录入"
case loginMethodPassword:
return "账号密码登录"
case loginMethodQRScan:
return "扫码登录"
default:
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)
}
}
+47
View File
@@ -0,0 +1,47 @@
package server
import (
"context"
"testing"
)
// TestMarkSuccessfulLoginUsesApplicationAuditService 验证 Server 仅调用应用审计服务并保持登录成功持久化语义。
func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) {
// srv、store 和 cleanup 保存带固定管理员账号的 HTTP 测试服务及资源清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// admin 保存触发登录审计的非敏感管理员身份。
admin, adminErr := store.Users.GetByUsername(context.Background(), "admin")
if adminErr != nil {
t.Fatal(adminErr)
}
// srv.markSuccessfulLogin 执行账号密码登录别名的成功审计。
srv.markSuccessfulLogin(context.Background(), "acc1", admin.ID, "password_login", "账号登录成功")
// summary 保存应用服务写入后的账号非敏感摘要。
summary, summaryErr := store.Cookies.GetSummaryOwned(context.Background(), admin.ID, "acc1")
if summaryErr != nil || summary.LoginMethod != loginMethodPassword || summary.LastLoginAt == 0 {
t.Fatalf("登录方式未由应用审计服务保存 summary=%+v err=%v", summary, summaryErr)
}
// logs 保存应用审计服务写入的数据库记录。
logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if logsErr != nil || len(logs) != 1 || logs[0].Method != loginMethodPassword || logs[0].Status != "success" || logs[0].TriggerReason != "账号密码登录" {
t.Fatalf("登录审计记录异常 logs=%+v err=%v", logs, logsErr)
}
}
// TestMarkSuccessfulLoginSkipsEmptyMethod 验证 Server 对缺少登录方式的兼容空操作不创建审计记录。
func TestMarkSuccessfulLoginSkipsEmptyMethod(t *testing.T) {
// srv、store 和 cleanup 保存 HTTP 测试服务及资源清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// srv.markSuccessfulLogin 执行缺少方式的兼容调用。
srv.markSuccessfulLogin(context.Background(), "acc1", 1, "", "不应记录")
// logs 保存兼容调用后的数据库审计记录。
logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if logsErr != nil {
t.Fatal(logsErr)
}
if len(logs) != 0 {
t.Fatalf("空登录方式不应写入审计记录: %+v", logs)
}
}
+10 -55
View File
@@ -2,42 +2,12 @@ package server
import (
"context"
"time"
"errors"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
// withMTopCookieSnapshot 为一次业务 MTOP 流程挂载账号 Cookie 会话。有完整
// Jar 时保持所有作用域;历史账号则使用不冒充完整 Jar 的 flat session,仍能
// 在成功或失败路径观察并持久化 Set-Cookie。
// withMTopCookieSnapshot 负责withMTop登录凭证Snapshot相关处理。
func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (context.Context, *mtop.CookieSession) {
if detail == nil {
return ctx, nil
}
// snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
return mtop.WithFlatCookieSession(ctx, detail.Value)
}
return mtop.WithCookieSnapshot(ctx, snapshot)
}
// hasStoredCookieCredential 负责hasStored登录凭证Credential相关处理。
func hasStoredCookieCredential(detail *db.CookieDetail) bool {
if detail == nil {
return false
}
if detail.Value != "" {
return true
}
// complete 保存complete,供当前处理流程使用
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
// persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。
// 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。
// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
@@ -46,28 +16,13 @@ func hasStoredCookieCredential(detail *db.CookieDetail) bool {
// persistMTopCookieSessionLocked 负责persistMTop登录凭证会话Locked相关处理。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *db.CookieDetail,
session *mtop.CookieSession,
detail *accountapp.CredentialDetail,
session *adapter.CookieSession,
) (value string, valueChanged, handled bool, err error) {
if detail == nil || session == nil {
return "", false, false, nil
if s == nil {
return "", false, true, errors.New("cookie 会话持久化服务未初始化")
}
// value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用
value, snapshot, changed := session.State()
if !changed {
if snapshot != nil {
return detail.Value, false, true, nil
}
return "", false, false, nil
}
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil {
return value, value != detail.Value, true, err
}
return value, value != detail.Value, true, nil
// repository 负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。
repository := s.accountLoginRepositoryForServer()
return adapter.PersistCookieSessionLocked(ctx, repository, detail, session)
}
+9 -4
View File
@@ -68,8 +68,13 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
if err != nil {
t.Fatal(err)
}
// message 保存消息,供当前处理流程使用
_, _, message := srv.refreshAccountProfile(ctx, detail)
// profile、profileErr 保存资料应用服务返回的非敏感结果和用例错误。
profile, profileErr := srv.accountProfileApplication().RefreshProfile(ctx, detail.UserID, detail.ID)
// message 保存资料刷新失败时的可展示错误文本。
message := profile.ErrorMessage
if profileErr != nil {
message = profileErr.Error()
}
if message == "" {
t.Fatal("无效响应应返回解析错误")
}
@@ -116,7 +121,7 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
_, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID)
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
@@ -149,7 +154,7 @@ func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T)
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
_, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID)
// updated、err 保存updated、err,供当前处理流程使用
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
+2 -193
View File
@@ -1,7 +1,6 @@
package server
import (
"context"
"errors"
"net/http"
"strconv"
@@ -10,7 +9,6 @@ import (
"github.com/go-chi/chi/v5"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
)
// notificationChannelCreateRequest 是创建通知渠道的具名 HTTP 请求 DTO;Config 只写入应用端口。
@@ -51,200 +49,11 @@ type notificationBindingRequest struct {
Enabled *bool `json:"enabled"`
}
// storeNotificationChannelRepository 将通知数据库能力适配为通知应用端口。
type storeNotificationChannelRepository struct {
// store 保存数据库聚合入口,仅在 Server 基础设施适配器内使用。
store *db.Store
}
// ListChannels 查询渠道摘要并丢弃配置,避免敏感配置进入应用展示模型。
func (r storeNotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) {
// rows、err 保存数据库渠道非敏感摘要;列表路径不会读取或解密 Config。
rows, err := r.store.Notifications.ListChannelSummariesForUser(ctx, userID)
if err != nil {
return nil, err
}
// summaries 保存不含渠道配置的应用摘要。
summaries := make([]notificationsapp.ChannelSummary, 0, len(rows))
// row 表示当前待转换的数据库渠道行。
for _, row := range rows {
summaries = append(summaries, notificationsapp.ChannelSummary{ID: row.ID, Name: row.Name, Type: row.Type, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID})
}
return summaries, nil
}
// GetChannelForUpdate 查询归属渠道的完整记录,仅供应用层合并部分更新。
func (r storeNotificationChannelRepository) GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*notificationsapp.ChannelRecord, error) {
// row、err 保存带用户归属的数据库渠道记录。
row, err := r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID)
if err != nil {
return nil, err
}
if row == nil {
return nil, nil
}
return &notificationsapp.ChannelRecord{ID: row.ID, Name: row.Name, Type: row.Type, Config: row.Config, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}, nil
}
// CreateChannel 将应用输入转换为数据库行并创建渠道。
func (r storeNotificationChannelRepository) CreateChannel(ctx context.Context, userID int64, input notificationsapp.ChannelInput) (int64, error) {
// row 保存待加密写入数据库的渠道行;Config 不向 HTTP 返回。
row := db.NotificationChannelRow{Name: input.Name, Type: input.Type, Config: input.Config, EventTypes: input.EventTypes, Enabled: input.Enabled, UserID: userID}
return r.store.Notifications.CreateChannel(ctx, &row)
}
// UpdateChannel 将应用层完整渠道记录转换为数据库更新。
func (r storeNotificationChannelRepository) UpdateChannel(ctx context.Context, userID int64, record notificationsapp.ChannelRecord) error {
// row 保存待加密写入数据库的渠道行;调用方已完成归属和字段校验。
row := db.NotificationChannelRow{ID: record.ID, Name: record.Name, Type: record.Type, Config: record.Config, EventTypes: record.EventTypes, Enabled: record.Enabled, UserID: userID}
return r.store.Notifications.UpdateChannelForUser(ctx, &row, userID)
}
// DeleteChannel 删除用户拥有的渠道并统一转换不存在错误。
func (r storeNotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID))
}
// OwnsChannel 查询通知渠道归属,不读取配置内容。
func (r storeNotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) {
return r.store.Notifications.OwnsChannel(ctx, channelID, userID)
}
// OwnsAccount 查询账号归属,不读取或解密 Cookie。
func (r storeNotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
}
// ListBindings 查询绑定摘要并转换为应用模型。
func (r storeNotificationChannelRepository) ListBindings(ctx context.Context, userID int64) ([]notificationsapp.BindingSummary, error) {
// rows、err 保存数据库绑定摘要及错误。
rows, err := r.store.Notifications.ListBindingsForUser(ctx, userID)
if err != nil {
return nil, err
}
// bindings 保存不含配置的应用绑定摘要。
bindings := make([]notificationsapp.BindingSummary, 0, len(rows))
// row 表示当前待转换的数据库绑定行。
for _, row := range rows {
bindings = append(bindings, notificationsapp.BindingSummary{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled})
}
return bindings, nil
}
// GetBindingIDs 查询账号启用的通知渠道 ID。
func (r storeNotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
return r.store.Notifications.AccountBindings(ctx, cookieID)
}
// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。
func (r storeNotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs))
}
// SetSingleBinding 更新单个账号绑定状态。
func (r storeNotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled)
}
// DeleteBinding 删除用户的一条绑定。
func (r storeNotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
return r.store.Notifications.DeleteBinding(ctx, userID, bindingID)
}
// DeleteAccountBindings 删除用户账号的全部绑定。
func (r storeNotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)
}
// normalizeNotificationRepositoryError 将数据库归属错误转换为应用错误,隐藏基础设施类型。
func normalizeNotificationRepositoryError(err error) error {
if errors.Is(err, db.ErrNotFound) {
return notificationsapp.ErrChannelNotFound
}
if errors.Is(err, db.ErrForbidden) {
return notificationsapp.ErrChannelForbidden
}
return err
}
// newStoreNotificationChannelRepository 构造通知渠道应用端口适配器。
func newStoreNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository {
if store == nil || store.Notifications == nil || store.Cookies == nil {
return nil
}
return storeNotificationChannelRepository{store: store}
}
// notificationChannelsApplication 返回当前 Server 绑定的通知渠道应用服务。
func (s *Server) notificationChannelsApplication() *notificationsapp.ChannelService {
return s.applicationServiceSet().notificationChannels
}
// ensureStoreNotificationChannelRepository 保证通知渠道应用端口覆盖全部能力。
var _ notificationsapp.ChannelRepository = storeNotificationChannelRepository{}
// storeNotificationUncertainRepository 将数据库通知摘要查询适配为应用层端口。
type storeNotificationUncertainRepository struct {
// store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。
store *db.Store
}
// ListUncertainForUser 查询指定用户的不确定通知摘要,并转换为应用模型。
func (r storeNotificationUncertainRepository) ListUncertainForUser(ctx context.Context, userID int64, limit int) ([]notificationsapp.UncertainSummary, error) {
// rows、err 保存数据库摘要查询结果及错误。
rows, err := r.store.Notifications.ListUncertainOutboxForUser(ctx, userID, limit)
if err != nil {
return nil, err
}
return newNotificationUncertainApplicationSummaries(rows), nil
}
// CountUncertainForUser 统计指定用户的不确定通知数量。
func (r storeNotificationUncertainRepository) CountUncertainForUser(ctx context.Context, userID int64) (int, error) {
return r.store.Notifications.CountUncertainOutboxForUser(ctx, userID)
}
// ListUncertainForAdmin 查询全局不确定通知摘要,并转换为应用模型。
func (r storeNotificationUncertainRepository) ListUncertainForAdmin(ctx context.Context, limit int) ([]notificationsapp.UncertainSummary, error) {
// rows、err 保存数据库全局摘要查询结果及错误。
rows, err := r.store.Notifications.ListUncertainOutboxForAdmin(ctx, limit)
if err != nil {
return nil, err
}
return newNotificationUncertainApplicationSummaries(rows), nil
}
// CountUncertainForAdmin 统计全局不确定通知数量。
func (r storeNotificationUncertainRepository) CountUncertainForAdmin(ctx context.Context) (int, error) {
return r.store.Notifications.CountUncertainOutboxForAdmin(ctx)
}
// newStoreNotificationUncertainRepository 创建通知不确定状态应用服务使用的数据库适配器。
func newStoreNotificationUncertainRepository(store *db.Store) notificationsapp.Repository {
if store == nil || store.Notifications == nil {
return nil
}
return storeNotificationUncertainRepository{store: store}
}
// newNotificationUncertainApplicationSummaries 将数据库摘要转换为不含正文的应用模型。
func newNotificationUncertainApplicationSummaries(rows []db.NotificationUncertainSummary) []notificationsapp.UncertainSummary {
// summaries 保存脱离数据库模型的非敏感通知摘要。
summaries := make([]notificationsapp.UncertainSummary, 0, len(rows))
// row 表示当前待转换的数据库通知摘要。
for _, row := range rows {
summaries = append(summaries, notificationsapp.UncertainSummary{
ID: row.ID, ChannelID: row.ChannelID, OwnerUserID: row.OwnerUserID,
EventType: row.EventType, AttemptCount: row.AttemptCount,
UncertainAt: row.UncertainAt, HasError: row.HasError,
})
}
return summaries
}
// 确保数据库适配器覆盖通知不确定状态应用端口的全部能力。
var _ notificationsapp.Repository = storeNotificationUncertainRepository{}
// uncertainNotificationsApplication 返回当前 Server 绑定的通知不确定状态应用服务。
func (s *Server) uncertainNotificationsApplication() *notificationsapp.Service {
return s.applicationServiceSet().uncertainNotifications
@@ -352,7 +161,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
@@ -374,7 +183,7 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
sess := authSess(r)
// err 保存应用层删除结果。
if err := s.notificationChannelsApplication().DeleteChannel(r.Context(), sess.UserID, id); err != nil {
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
+7 -68
View File
@@ -1,7 +1,6 @@
package server
import (
"context"
"errors"
"fmt"
"net/http"
@@ -11,27 +10,17 @@ import (
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// refreshOrderChunkSize 保存refresh订单Chunk数量,供当前处理流程使用
const refreshOrderChunkSize = 100
// maxSoldOrderPages 保存maxSold订单Pages,供当前处理流程使用
const maxSoldOrderPages = 100
// refreshTarget 保存refreshTarget,供当前处理流程使用
type refreshTarget struct {
OrderID string
CurrentStatus string
}
// orderDetailMTop 保存订单DetailMTop,供当前处理流程使用
type orderDetailMTop interface {
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
}
// mountOrders 订单端点(真实实现)。
func (s *Server) mountOrdersReal(r chi.Router) {
r.Get("/api/orders", s.listOrders)
@@ -54,7 +43,7 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
Status: r.URL.Query().Get("status"), Search: r.URL.Query().Get("search"),
Page: atoiDefault(r.URL.Query().Get("page"), 1), PageSize: atoiDefault(r.URL.Query().Get("page_size"), 20),
})
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
@@ -81,7 +70,7 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().GetView(r.Context(), sess.UserID, orderID)
if err != nil {
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
} else {
writeErr(w, http.StatusNotFound, "订单不存在")
@@ -132,11 +121,11 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { //
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().RefreshSingle(r.Context(), sess.UserID, orderID)
if errors.Is(err, db.ErrNotFound) {
if errors.Is(err, orderapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "订单不存在")
return
}
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
return
}
@@ -167,7 +156,7 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.orders().Delete(r.Context(), sess.UserID, orderID); err != nil {
if errors.Is(err, db.ErrForbidden) {
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
} else {
writeErr(w, http.StatusNotFound, "订单不存在")
@@ -232,9 +221,9 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
if // kind、classified 保存kind、classified,供当前处理流程使用
kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest {
writeErr(w, http.StatusBadRequest, err.Error())
} else if errors.Is(err, db.ErrForbidden) {
} else if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
} else if errors.Is(err, db.ErrNotFound) {
} else if errors.Is(err, orderapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "订单不存在")
} else {
writeErr(w, http.StatusInternalServerError, "更新失败")
@@ -297,56 +286,6 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
}
// consignWithCurrentCookie 负责consignWithCurrent登录凭证相关处理。
func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
defer credentialUnlock()
// detail、err 保存detail、err,供当前处理流程使用
detail, err := s.loadCookiePlatformDetail(ctx, cookieID)
if err != nil {
return false, nil, "", false, err
}
if detail == nil || detail.UserID != userID {
return false, nil, "", false, db.ErrForbidden
}
if !hasStoredCookieCredential(detail) {
return false, nil, "", false, errors.New("账号 Cookie 为空")
}
// mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, detail)
// ok、ret、updatedCookies、callErr 保存ok、ret、updatedCookies、callErr,供当前处理流程使用
ok, ret, updatedCookies, callErr := s.MTop.ConsignContext(mtopCtx, detail.Value, orderID)
// value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, detail, cookieSession)
if persistErr != nil {
persistErr = fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr)
if callErr != nil {
return ok, ret, "", false, errors.Join(callErr, persistErr)
}
return ok, ret, "", false, persistErr
}
if handled {
// runtimeCookie 保存runtime登录凭证,供当前处理流程使用
runtimeCookie := ""
if valueChanged {
runtimeCookie = value
}
return ok, ret, runtimeCookie, valueChanged, callErr
}
if callErr != nil {
return false, ret, "", false, callErr
}
if updatedCookies == "" || updatedCookies == detail.Value {
return ok, ret, "", false, nil
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return ok, ret, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err)
}
return ok, ret, updatedCookies, true, nil
}
// importOrders 负责import订单列表相关处理。
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
// orders、err 保存orders、err,供当前处理流程使用
+4 -2
View File
@@ -12,6 +12,7 @@ import (
"testing"
"time"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
@@ -1101,9 +1102,10 @@ func stringPtrForOrderTest(value string) *string {
// TestOrderResponseMappingAndErrorClassification 验证订单响应映射和业务错误分类不依赖 HTTP。
func TestOrderResponseMappingAndErrorClassification(t *testing.T) {
// row 保存row,供当前处理流程使用
row := db.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"}
// row 保存应用层订单列表模型,模拟适配器已经完成数据库转换。
row := orderapp.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"}
// view 保存view,供当前处理流程使用
view := orderDTOFromRow(orderRowsFromDB([]db.OrderRow{row})[0])
view := orderDTOFromRow(row)
if view.OrderStatus != "pending_ship" || view.Status != "pending_ship" || view.ItemImage != "https://img.example/mapped.png" {
t.Fatalf("订单响应映射异常: %+v", view)
}
+3 -81
View File
@@ -4,73 +4,11 @@ import (
"reflect"
"testing"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// TestOrderModelConversions 保证订单边界转换完整保留业务字段并正确处理空值。
func TestOrderModelConversions(t *testing.T) {
// databaseOrder 是模拟数据库读取到的完整订单实体。
databaseOrder := &db.Order{
OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色",
SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship",
CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000",
ReceiverAddr: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1",
SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed",
BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2,
CreatedAt: "created", UpdatedAt: "updated",
}
// applicationOrder 是订单应用层实体的预期结果。
applicationOrder := &orderapp.Order{
OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色",
SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship",
CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000",
ReceiverAddress: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1",
SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed",
BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2,
CreatedAt: "created", UpdatedAt: "updated",
}
// converted 是数据库订单转换后的应用订单。
converted := orderFromDB(databaseOrder)
if !reflect.DeepEqual(converted, applicationOrder) {
t.Fatalf("订单转换结果不完整: got=%+v want=%+v", converted, applicationOrder)
}
if orderFromDB(nil) != nil {
t.Fatal("空数据库订单应转换为空应用订单")
}
// databaseItem 是模拟数据库读取到的完整商品实体。
databaseItem := &db.ItemInfo{
ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品",
ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`,
IsMultiSpec: true, MultiQuantityDelivery: true,
}
// applicationItem 是商品应用层实体的预期结果。
applicationItem := &orderapp.ItemInfo{
ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品",
ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`,
IsMultiSpec: true, MultiQuantityDelivery: true,
}
// convertedItem 是数据库商品转换后的应用商品。
convertedItem := itemInfoFromDB(databaseItem)
if !reflect.DeepEqual(convertedItem, applicationItem) {
t.Fatalf("商品转换结果不完整: got=%+v want=%+v", convertedItem, applicationItem)
}
if itemInfoFromDB(nil) != nil {
t.Fatal("空数据库商品应转换为空应用商品")
}
// databaseRuntime 是模拟数据库读取到的平台运行视图。
databaseRuntime := db.CookiePlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true}
// applicationRuntime 是平台运行视图的预期应用层结果。
applicationRuntime := &orderapp.PlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true}
// convertedRuntime 是数据库平台运行视图转换后的应用模型。
convertedRuntime := platformRuntimeDataFromDB(databaseRuntime)
if !reflect.DeepEqual(convertedRuntime, applicationRuntime) {
t.Fatalf("平台运行视图转换结果不完整: got=%+v want=%+v", convertedRuntime, applicationRuntime)
}
}
// TestOrderForAutomation 保证未迁移的自动化边界不会丢失订单字段。
func TestOrderForAutomation(t *testing.T) {
// applicationOrder 是传入自动化中心适配器的应用订单。
@@ -84,27 +22,11 @@ func TestOrderForAutomation(t *testing.T) {
CookieID: "cookie-2", ChatID: "chat-2", OrderStatus: "pending_ship", Version: 4,
}
// converted 是传给自动化中心的数据库订单。
converted := orderForAutomation(applicationOrder)
converted := adapter.OrderForAutomation(applicationOrder)
if !reflect.DeepEqual(converted, expectedDatabaseOrder) {
t.Fatalf("自动化边界订单转换错误: got=%+v want=%+v", converted, expectedDatabaseOrder)
}
if orderForAutomation(nil) != nil {
if adapter.OrderForAutomation(nil) != nil {
t.Fatal("空应用订单应转换为空数据库订单")
}
}
// TestCookieDetailForOrderPlatform 保证订单刷新访问共享会话辅助函数时只映射最小字段。
func TestCookieDetailForOrderPlatform(t *testing.T) {
// runtimeData 是订单应用层持有的平台运行视图。
runtimeData := &orderapp.PlatformRuntimeData{ID: "cookie-3", UserID: 11, Value: "value", MetadataJSON: "metadata", ShowBrowser: true}
// expectedDetail 是共享 Server 会话辅助函数使用的兼容详情。
expectedDetail := &db.CookieDetail{ID: "cookie-3", UserID: 11, Value: "value", MetadataJSON: "metadata", ShowBrowser: true}
// converted 是共享 Server 会话辅助函数使用的平台详情。
converted := cookieDetailForOrderPlatform(runtimeData)
if !reflect.DeepEqual(converted, expectedDetail) {
t.Fatalf("平台详情边界转换错误: got=%+v want=%+v", converted, expectedDetail)
}
if cookieDetailForOrderPlatform(nil) != nil {
t.Fatal("空平台运行视图应转换为空平台详情")
}
}
+102 -18
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
@@ -61,6 +62,18 @@ type orderRefreshWorker struct {
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)
@@ -176,15 +189,26 @@ func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string)
// parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。
parent := s.lifecycleContext()
if parent == nil {
parent = context.Background()
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.startBackgroundTask("订单刷新任务", func() {
s.startBackgroundTaskResult("订单刷新任务", jobCtx, func() error {
defer cancel()
defer s.unregisterOrderRefreshWorker(job.ID, token)
s.runOrderRefreshJob(jobCtx, job, 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
})
}
@@ -228,26 +252,67 @@ func (s *Server) cancelOrderRefreshWorker(jobID string) bool {
}
// runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。
func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) {
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 := s.orders().Refresh(ctx, job.UserID, job.CookieID, job.FilterStatus)
result, err := refresh(ctx, job.UserID, job.CookieID, job.FilterStatus)
if err != nil {
// completeErr 表示失败终态写入错误。
if _, completeErr := s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", err.Error()); completeErr != nil && s.Logger != nil {
s.Logger.Warn("写入订单刷新失败终态失败", "job_id", job.ID, "err", completeErr)
// completeErr 保存失败终态写入错误。
completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", err.Error())
if completeErr != nil {
return errors.Join(err, completeErr)
}
return
return err
}
// resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。
resultJSON, marshalErr := json.Marshal(result)
resultJSON, marshalErr := marshal(result)
if marshalErr != nil {
_, _ = s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", marshalErr.Error())
return
// completeErr 保存序列化失败终态写入错误。
completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", marshalErr.Error())
if completeErr != nil {
return errors.Join(marshalErr, completeErr)
}
return marshalErr
}
// completeErr 表示成功终态写入错误。
if _, completeErr := s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "succeeded", string(resultJSON), ""); completeErr != nil && s.Logger != nil {
s.Logger.Warn("写入订单刷新成功终态失败", "job_id", job.ID, "err", completeErr)
// 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 扫描并重新执行租约过期的订单刷新任务。
@@ -287,15 +352,34 @@ func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) {
for _, job := range jobs {
// requeued、requeueErr 保存重新入队结果及错误。
requeued, requeueErr := s.orders().services.RefreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix())
if requeueErr != nil || !requeued {
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 && claimed {
s.startOrderRefreshWorker(&job, token)
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)
}
}
@@ -0,0 +1,260 @@
package server
import (
"context"
"encoding/json"
"errors"
"testing"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// orderRefreshLifecycleContextKey 是生命周期测试专用的 Context 键类型,避免与生产或其他测试键冲突。
type orderRefreshLifecycleContextKey struct{}
// newOrderRefreshJobLifecycleFixture 创建生命周期测试共用的应用任务模型。
func newOrderRefreshJobLifecycleFixture() *orderapp.RefreshJob {
return &orderapp.RefreshJob{ID: "refresh-lifecycle-job", UserID: 7, CookieID: "cookie-1", FilterStatus: "pending_ship"}
}
// TestRunOrderRefreshJobWithSuccess 验证业务成功后会写入成功终态和序列化结果。
func TestRunOrderRefreshJobWithSuccess(t *testing.T) {
// ctx 是本用例传递给业务和终态写入的生命周期上下文。
ctx := context.WithValue(context.Background(), orderRefreshLifecycleContextKey{}, "lifecycle")
// job 是待执行的订单刷新任务。
job := newOrderRefreshJobLifecycleFixture()
// result 是业务刷新返回的确定性结果。
result := orderRefreshResponse{Message: "刷新完成", Summary: orderRefreshSummary{Total: 1}}
// completed 表示终态写入是否被调用。
completed := false
// status 保存终态写入的目标状态。
status := ""
// resultJSON 保存终态写入的序列化结果。
resultJSON := ""
// refresh 是成功返回固定结果的业务回调。
refresh := func(gotCtx context.Context, userID int64, cookieID, filterStatus string) (orderRefreshResponse, error) {
if gotCtx != ctx || userID != job.UserID || cookieID != job.CookieID || filterStatus != job.FilterStatus {
t.Fatalf("刷新回调参数不正确: ctx=%p user=%d cookie=%s status=%s", gotCtx, userID, cookieID, filterStatus)
}
return result, nil
}
// marshal 是使用标准 JSON 编码器的确定性序列化回调。
marshal := func(value any) ([]byte, error) { return json.Marshal(value) }
// complete 是记录终态写入参数的成功回调。
complete := func(gotCtx context.Context, jobID, token, gotStatus, gotResultJSON, errorMessage string) (bool, error) {
if gotCtx != ctx || jobID != job.ID || token != "token-1" || errorMessage != "" {
t.Fatalf("终态写入参数不正确: ctx=%p job=%s token=%s status=%s error=%s", gotCtx, jobID, token, gotStatus, errorMessage)
}
completed, status, resultJSON = true, gotStatus, gotResultJSON
return true, nil
}
// err 保存 worker 执行错误。
err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete)
if err != nil {
t.Fatalf("成功刷新不应返回错误: %v", err)
}
if !completed || status != "succeeded" || resultJSON == "" {
t.Fatalf("成功终态未写入: completed=%v status=%s result=%s", completed, status, resultJSON)
}
}
// TestRunOrderRefreshJobWithBusinessFailure 验证业务错误会写入失败终态并原样返回。
func TestRunOrderRefreshJobWithBusinessFailure(t *testing.T) {
// ctx 是本用例传递给业务和终态写入的上下文。
ctx := context.Background()
// job 是待执行的订单刷新任务。
job := newOrderRefreshJobLifecycleFixture()
// businessErr 是业务刷新失败的根因。
businessErr := errors.New("订单平台请求失败")
// failedStatus 保存失败终态写入状态。
failedStatus := ""
// failedMessage 保存失败终态写入的业务错误文本。
failedMessage := ""
// refresh 是返回预置业务错误的刷新回调。
refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) {
return orderRefreshResponse{}, businessErr
}
// marshal 是不会被业务失败路径调用的序列化回调。
marshal := func(any) ([]byte, error) {
t.Fatal("业务失败不应尝试序列化成功结果")
return nil, nil
}
// complete 是记录失败终态的回调。
complete := func(_ context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) {
if jobID != job.ID || token != "token-1" || resultJSON != "{}" {
t.Fatalf("失败终态参数不正确: job=%s token=%s result=%s", jobID, token, resultJSON)
}
failedStatus, failedMessage = status, errorMessage
return true, nil
}
// err 保存 worker 执行错误。
err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete)
if !errors.Is(err, businessErr) || failedStatus != "failed" || failedMessage != businessErr.Error() {
t.Fatalf("业务失败终态不正确: err=%v status=%s message=%s", err, failedStatus, failedMessage)
}
}
// TestRunOrderRefreshJobWithSerializationFailure 验证序列化失败会写入失败终态。
func TestRunOrderRefreshJobWithSerializationFailure(t *testing.T) {
// ctx 是本用例传递给业务和终态写入的上下文。
ctx := context.Background()
// job 是待执行的订单刷新任务。
job := newOrderRefreshJobLifecycleFixture()
// marshalErr 是结果序列化失败的根因。
marshalErr := errors.New("结果序列化失败")
// failedStatus 保存序列化失败后的终态状态。
failedStatus := ""
// refresh 是返回固定成功结果的刷新回调。
refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) {
return orderRefreshResponse{Message: "完成"}, nil
}
// marshal 是返回预置序列化错误的回调。
marshal := func(any) ([]byte, error) { return nil, marshalErr }
// complete 是记录失败终态的回调。
complete := func(_ context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) {
if jobID != job.ID || token != "token-1" || resultJSON != "{}" || errorMessage != marshalErr.Error() {
t.Fatalf("序列化失败终态参数不正确: job=%s token=%s result=%s error=%s", jobID, token, resultJSON, errorMessage)
}
failedStatus = status
return true, nil
}
// err 保存 worker 执行错误。
err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete)
if !errors.Is(err, marshalErr) || failedStatus != "failed" {
t.Fatalf("序列化失败未正确收束: err=%v status=%s", err, failedStatus)
}
}
// TestRunOrderRefreshJobWithCompletionFailure 验证终态数据库错误和租约失配不会被吞掉。
func TestRunOrderRefreshJobWithCompletionFailure(t *testing.T) {
// ctx 是本用例传递给业务和终态写入的上下文。
ctx := context.Background()
// job 是待执行的订单刷新任务。
job := newOrderRefreshJobLifecycleFixture()
// writeErr 是终态持久化返回的数据库错误。
writeErr := errors.New("数据库写入失败")
// refresh 是返回固定成功结果的刷新回调。
refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) {
return orderRefreshResponse{Message: "完成"}, nil
}
// marshal 是使用标准 JSON 编码器的序列化回调。
marshal := func(value any) ([]byte, error) { return json.Marshal(value) }
// completeWithError 是返回数据库错误的终态写入回调。
completeWithError := func(context.Context, string, string, string, string, string) (bool, error) {
return false, writeErr
}
// err 保存数据库错误场景的 worker 执行错误。
err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, completeWithError)
if !errors.Is(err, writeErr) {
t.Fatalf("终态数据库错误未返回: %v", err)
}
// completeUnapplied 是返回租约未命中的终态写入回调。
completeUnapplied := func(context.Context, string, string, string, string, string) (bool, error) {
return false, nil
}
// unappliedErr 保存租约未命中场景的 worker 执行错误。
unappliedErr := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, completeUnapplied)
if !errors.Is(unappliedErr, errOrderRefreshJobCompletionNotApplied) {
t.Fatalf("终态未生效未转换为可观测错误: %v", unappliedErr)
}
}
// TestRunOrderRefreshJobWithCancellation 验证取消后的业务和终态写入都继承同一个已取消 Context。
func TestRunOrderRefreshJobWithCancellation(t *testing.T) {
// ctx、cancel 是 Server 生命周期取消信号及其触发函数。
ctx, cancel := context.WithCancel(context.Background())
cancel()
// job 是待执行的订单刷新任务。
job := newOrderRefreshJobLifecycleFixture()
// completionCtx 保存终态写入收到的上下文。
var completionCtx context.Context
// refresh 是确认业务收到取消信号的回调。
refresh := func(gotCtx context.Context, _ int64, _, _ string) (orderRefreshResponse, error) {
if gotCtx != ctx || !errors.Is(gotCtx.Err(), context.Canceled) {
t.Fatalf("业务未继承取消 Context: ctx=%p err=%v", gotCtx, gotCtx.Err())
}
return orderRefreshResponse{}, context.Canceled
}
// marshal 是不会被取消业务路径调用的序列化回调。
marshal := func(any) ([]byte, error) {
t.Fatal("取消业务不应尝试序列化成功结果")
return nil, nil
}
// complete 是模拟数据库遵循 Context 取消的终态写入回调。
complete := func(gotCtx context.Context, _ string, _ string, _ string, _ string, _ string) (bool, error) {
completionCtx = gotCtx
return false, gotCtx.Err()
}
// err 保存取消场景的 worker 执行错误。
err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete)
if completionCtx != ctx || !errors.Is(err, context.Canceled) {
t.Fatalf("取消错误或 Context 未保留: ctx=%p completion=%p err=%v", ctx, completionCtx, err)
}
}
// TestOrderRefreshWorkerUsesCanceledServerLifecycle 验证 Server 关闭后 worker 不会使用脱离生命周期的 Context 写终态。
func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) {
// srv、store、cleanup 保存测试服务、数据库和清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// lifecycleCtx、cancel 是已取消的 Server 生命周期上下文。
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 {
t.Fatalf("读取管理员: %v", err)
}
// dbJob 保存数据库层待执行任务。
dbJob := &db.OrderRefreshJob{ID: "refresh-canceled-lifecycle", UserID: admin.ID}
// err 保存创建任务错误。
if err := store.OrderRefreshJobs.Create(context.Background(), dbJob); err != nil {
t.Fatalf("创建刷新任务: %v", err)
}
// token 是当前 worker 的租约令牌。
token := "refresh-canceled-token"
// claimed、err 保存任务抢占结果及错误。
claimed, err := store.OrderRefreshJobs.Claim(context.Background(), dbJob.ID, token, 9999999999)
if err != nil || !claimed {
t.Fatalf("抢占刷新任务: claimed=%v err=%v", claimed, err)
}
// job 是传给后台 worker 的应用层任务模型。
job := &orderapp.RefreshJob{ID: dbJob.ID, UserID: dbJob.UserID}
srv.startOrderRefreshWorker(job, token)
srv.WaitForBackground()
// persisted、err 保存 worker 结束后的任务状态及查询错误。
persisted, err := store.OrderRefreshJobs.Get(context.Background(), admin.ID, dbJob.ID)
if err != nil {
t.Fatalf("读取取消后的任务: %v", err)
}
if persisted.Status != "running" {
t.Fatalf("取消生命周期后不应使用后台 Context 覆盖租约状态: %+v", persisted)
}
}
// TestStartBackgroundTaskResultTracksFailure 验证后台任务错误会进入 Server 任务状态。
func TestStartBackgroundTaskResultTracksFailure(t *testing.T) {
// srv 是只装配任务注册表的最小 Server 生命周期实例。
srv := &Server{taskRegistry: newTaskRegistry()}
// taskErr 是后台任务返回的确定性错误。
taskErr := errors.New("后台任务失败")
// taskID 是登记后用于读取任务状态的进程内标识。
taskID := srv.startBackgroundTaskResult("订单刷新测试任务", context.Background(), func() error {
return taskErr
})
srv.WaitForBackground()
// snapshots 保存任务注册表返回的状态快照。
snapshots := srv.taskRegistry.list()
if len(snapshots) != 1 || snapshots[0].ID != taskID || snapshots[0].State != taskStateFailed {
t.Fatalf("后台任务失败状态未记录: %+v", snapshots)
}
}
-399
View File
@@ -1,399 +0,0 @@
package server
import (
"context"
"database/sql"
"errors"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// storeOrderRepository 将完整 Store 适配为订单应用服务窄 repository。
type storeOrderRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// ExistsOwned 委托账号归属查询。
func (r storeOrderRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
}
// ListOwnedIDs 委托用户账号列表查询。
func (r storeOrderRepository) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) {
return r.store.Cookies.ListOwnedIDs(ctx, userID)
}
// ListOrdersForUser 委托用户订单列表查询。
func (r storeOrderRepository) ListOrdersForUser(ctx context.Context, filter orderapp.ListFilter) ([]orderapp.OrderRow, int, error) {
// rows、total、err 是数据库订单列表查询结果及其错误。
rows, total, err := r.store.Orders.ListForUser(ctx, db.OrderListFilter{
UserID: filter.UserID, CookieID: filter.CookieID, Status: filter.Status,
Search: filter.Search, Limit: filter.Limit, Offset: filter.Offset,
})
if err != nil {
return nil, 0, err
}
return orderRowsFromDB(rows), total, nil
}
// orderRowsFromDB 将数据库列表模型转换为订单应用层模型。
func orderRowsFromDB(rows []db.OrderRow) []orderapp.OrderRow {
// converted 保存转换后的应用层订单行。
converted := make([]orderapp.OrderRow, 0, len(rows))
for _, row := range rows { // row 是待转换的数据库订单列表行。
converted = append(converted, orderapp.OrderRow{
OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle,
ItemDetail: row.ItemDetail, BuyerID: row.BuyerID, SpecName: row.SpecName,
SpecValue: row.SpecValue, Quantity: row.Quantity, Amount: row.Amount,
OrderStatus: row.OrderStatus, CookieID: row.CookieID, IsBargain: row.IsBargain,
SystemShipped: row.SystemShipped, ReceiverName: row.ReceiverName,
ReceiverPhone: row.ReceiverPhone, ReceiverAddr: row.ReceiverAddr,
ReceiverCity: row.ReceiverCity, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
})
}
return converted
}
// orderFromDB 将数据库订单实体转换为不暴露存储层字段命名的应用实体。
func orderFromDB(order *db.Order) *orderapp.Order {
if order == nil {
return nil
}
return &orderapp.Order{
OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID,
SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity,
Amount: order.Amount, OrderStatus: order.OrderStatus, CookieID: order.CookieID,
IsBargain: order.IsBargain, ReceiverName: order.ReceiverName,
ReceiverPhone: order.ReceiverPhone, ReceiverAddress: order.ReceiverAddr,
ReceiverCity: order.ReceiverCity, Version: order.Version, ChatID: order.ChatID,
SystemShipped: order.SystemShipped, PaidAt: order.PaidAt, ShippedAt: order.ShippedAt,
CompletedAt: order.CompletedAt, BuyerReviewedAt: order.BuyerReviewedAt,
LastReviewRequestAt: order.LastReviewRequestAt, ReviewRequestCount: order.ReviewRequestCount,
CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt,
}
}
// itemInfoFromDB 将数据库商品实体转换为订单应用层商品模型。
func itemInfoFromDB(item *db.ItemInfo) *orderapp.ItemInfo {
if item == nil {
return nil
}
return &orderapp.ItemInfo{
ID: item.ID, CookieID: item.CookieID, ItemID: item.ItemID,
ItemTitle: item.ItemTitle, ItemDescription: item.ItemDescription,
ItemCategory: item.ItemCategory, ItemPrice: item.ItemPrice,
ItemDetail: item.ItemDetail, IsMultiSpec: item.IsMultiSpec,
MultiQuantityDelivery: item.MultiQuantityDelivery,
}
}
// platformRuntimeDataFromDB 将数据库平台运行视图转换为订单应用层模型。
func platformRuntimeDataFromDB(data db.CookiePlatformRuntimeData) *orderapp.PlatformRuntimeData {
return &orderapp.PlatformRuntimeData{
ID: data.ID, UserID: data.UserID, Value: data.Value,
MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser,
}
}
// GetOrder 委托订单详情查询。
func (r storeOrderRepository) GetOrder(ctx context.Context, orderID string) (*orderapp.Order, error) {
// order 和 err 保存数据库订单查询结果及其错误。
order, err := r.store.Orders.Get(ctx, orderID)
if err != nil {
return nil, err
}
return orderFromDB(order), nil
}
// FindOrder 委托订单查询并把数据库的不存在错误转换为 exists=false。
func (r storeOrderRepository) FindOrder(ctx context.Context, orderID string) (*orderapp.Order, bool, error) {
// order、err 保存数据库订单查询结果及其错误。
order, err := r.store.Orders.Get(ctx, orderID)
if errors.Is(err, db.ErrNotFound) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
return orderFromDB(order), true, nil
}
// FindOrdersByIDs 委托数据库批量读取订单并转换为应用实体。
func (r storeOrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []string) (map[string]*orderapp.Order, error) {
// orders、err 保存数据库批量订单及查询错误。
orders, err := r.store.Orders.FindByIDs(ctx, orderIDs)
if err != nil {
return nil, err
}
// converted 保存转换后的应用订单索引。
converted := make(map[string]*orderapp.Order, len(orders))
// orderID、order 保存当前数据库订单的标识和实体。
for orderID, order := range orders {
converted[orderID] = orderFromDB(order)
}
return converted, nil
}
// GetItem 委托商品信息查询。
func (r storeOrderRepository) GetItem(ctx context.Context, cookieID, itemID string) (*orderapp.ItemInfo, error) {
// item 和 err 保存数据库商品查询结果及其错误。
item, err := r.store.Items.Get(ctx, cookieID, itemID)
if err != nil {
return nil, err
}
return itemInfoFromDB(item), nil
}
// SoftDeleteOrder 委托订单逻辑删除。
func (r storeOrderRepository) SoftDeleteOrder(ctx context.Context, orderID string) (bool, error) {
return r.store.Orders.SoftDelete(ctx, orderID)
}
// WithTransaction 创建、提交或回滚订单事务。
func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(orderapp.Writer) error) error {
// tx 和 err 保存事务创建结果。
tx, err := r.store.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
// committed 标识事务是否已经提交成功。
committed := false
defer func() {
if !committed {
_ = tx.Rollback()
}
}()
// writer 是隐藏数据库事务细节的订单写入适配器。
writer := storeOrderWriter{store: r.store, tx: tx}
// err 保存事务工作函数的执行错误。
if err := work(writer); err != nil {
return err
}
// err 保存事务提交错误。
if err := tx.Commit(); err != nil {
return err
}
committed = true
return nil
}
// storeOrderWriter 将订单应用写入模型适配为数据库事务操作。
type storeOrderWriter struct {
// store 保存数据库 repository 聚合入口。
store *db.Store
// tx 保存当前事务,仅在基础设施适配器内部可见。
tx *sql.Tx
}
// PatchOrder 委托事务内订单更新。
func (w storeOrderWriter) PatchOrder(ctx context.Context, orderID string, patch orderapp.OrderPatch) error {
return w.store.Orders.PatchTx(ctx, w.tx, orderID, db.OrderPatch{
OrderStatus: patch.OrderStatus, ItemID: patch.ItemID, BuyerID: patch.BuyerID,
SpecName: patch.SpecName, SpecValue: patch.SpecValue, Quantity: patch.Quantity,
Amount: patch.Amount, ReceiverName: patch.ReceiverName, ReceiverPhone: patch.ReceiverPhone,
ReceiverAddr: patch.ReceiverAddress, ReceiverCity: patch.ReceiverCity, ChatID: patch.ChatID,
SystemShipped: patch.SystemShipped,
})
}
// UpsertItemBasic 委托事务内商品基础信息写入。
func (w storeOrderWriter) UpsertItemBasic(ctx context.Context, item orderapp.ItemWrite) error {
return w.store.Items.UpsertBasicTx(ctx, w.tx, &db.ItemInfoRow{
CookieID: item.CookieID, ItemID: item.ItemID, ItemTitle: item.ItemTitle,
ItemPrice: item.ItemPrice, ItemDetail: item.ItemDetail,
})
}
// UpsertOrder 委托事务内订单写入。
func (w storeOrderWriter) UpsertOrder(ctx context.Context, orderID string, options orderapp.UpsertOptions) error {
return w.store.Orders.UpsertTx(ctx, w.tx, orderID, db.OrderUpsertOpts{
ItemID: options.ItemID, BuyerID: options.BuyerID, CookieID: options.CookieID,
OrderStatus: options.OrderStatus, SpecName: options.SpecName, SpecValue: options.SpecValue,
Quantity: options.Quantity, Amount: options.Amount, ReceiverName: options.ReceiverName,
ReceiverPhone: options.ReceiverPhone, ReceiverAddr: options.ReceiverAddress,
ReceiverCity: options.ReceiverCity, ChatID: options.ChatID,
IsBargain: options.IsBargain, SystemShipped: options.SystemShipped,
})
}
// UpsertOrder 委托订单写入。
func (r storeOrderRepository) UpsertOrder(ctx context.Context, orderID string, opts orderapp.UpsertOptions) error {
return r.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
ItemID: opts.ItemID, BuyerID: opts.BuyerID, CookieID: opts.CookieID,
OrderStatus: opts.OrderStatus, SpecName: opts.SpecName, SpecValue: opts.SpecValue,
Quantity: opts.Quantity, Amount: opts.Amount, ReceiverName: opts.ReceiverName,
ReceiverPhone: opts.ReceiverPhone, ReceiverAddr: opts.ReceiverAddress,
ReceiverCity: opts.ReceiverCity, ChatID: opts.ChatID,
IsBargain: opts.IsBargain, SystemShipped: opts.SystemShipped,
})
}
// BatchUpsertOrders 委托订单详情分片的单条多值 UPSERT。
func (r storeOrderRepository) BatchUpsertOrders(ctx context.Context, rows []orderapp.RefreshOrderWrite) error {
if len(rows) == 0 {
return nil
}
// converted 保存数据库批量写入模型。
converted := make([]db.BatchOrderUpsert, 0, len(rows))
// row 是当前待转换的应用层批量订单记录。
for _, row := range rows {
converted = append(converted, db.BatchOrderUpsert{OrderID: row.OrderID, Options: db.OrderUpsertOpts{ItemID: row.Options.ItemID, BuyerID: row.Options.BuyerID, CookieID: row.Options.CookieID, OrderStatus: row.Options.OrderStatus, SpecName: row.Options.SpecName, SpecValue: row.Options.SpecValue, Quantity: row.Options.Quantity, Amount: row.Options.Amount, ReceiverName: row.Options.ReceiverName, ReceiverPhone: row.Options.ReceiverPhone, ReceiverAddr: row.Options.ReceiverAddress, ReceiverCity: row.Options.ReceiverCity, ChatID: row.Options.ChatID, IsBargain: row.Options.IsBargain, SystemShipped: row.Options.SystemShipped}})
}
// tx、err 保存详情分片事务及创建错误。
tx, err := r.store.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
// committed 表示详情分片事务是否已经提交。
committed := false
defer func() {
if !committed {
_ = tx.Rollback()
}
}()
// err 保存批量订单写入错误。
if err := r.store.Orders.UpsertManyTx(ctx, tx, converted); err != nil {
return err
}
// err 保存详情分片事务提交错误。
if err := tx.Commit(); err != nil {
return err
}
committed = true
return nil
}
// LockCredentials 委托账号凭证锁。
func (r storeOrderRepository) LockCredentials(cookieID string) func() {
return r.store.LockAccountCredentials(cookieID)
}
// LoadCookiePlatformDetail 委托平台凭证详情查询。
func (r storeOrderRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*orderapp.PlatformRuntimeData, error) {
// data 和 err 保存平台运行视图查询结果。
data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if err != nil {
return nil, err
}
return platformRuntimeDataFromDB(data), nil
}
// UpdateRenewalCookie 委托续期 Cookie 更新。
func (r storeOrderRepository) UpdateRenewalCookie(ctx context.Context, cookieID, value, metadata string, at int64) error {
return r.store.Cookies.UpdateRenewalCookie(ctx, cookieID, value, metadata, at)
}
// SoftDeleteMissingOrders 委托账号远端缺失订单清理。
func (r storeOrderRepository) SoftDeleteMissingOrders(ctx context.Context, cookieID string, activeIDs map[string]struct{}) (int, error) {
return r.store.Orders.SoftDeleteMissingForCookie(ctx, cookieID, activeIDs)
}
// ListOrdersByCookieCursor 委托订单复合游标查询并转换应用层模型。
func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cookieID string, limit int, afterCreatedAt, afterOrderID string) ([]orderapp.OrderRow, error) {
// rows、err 保存数据库游标查询结果及错误。
rows, err := r.store.Orders.ByCookieCursor(ctx, cookieID, limit, afterCreatedAt, afterOrderID)
if err != nil {
return nil, err
}
return orderRowsFromDB(rows), nil
}
// Create 创建订单刷新后台任务并同步应用层模型默认值。
func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error {
// dbJob 保存待写入的数据库任务模型。
dbJob := &db.OrderRefreshJob{
ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus,
Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage,
WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt,
}
// err 表示数据库任务创建错误。
if err := r.store.OrderRefreshJobs.Create(ctx, dbJob); err != nil {
return err
}
job.Status, job.ResultJSON = dbJob.Status, dbJob.ResultJSON
return nil
}
// Get 按用户读取订单刷新后台任务并转换为应用层模型。
func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) {
// job、err 保存数据库任务读取结果及错误。
job, err := r.store.OrderRefreshJobs.Get(ctx, userID, id)
if errors.Is(err, db.ErrNotFound) {
return nil, orderapp.ErrRefreshJobNotFound
}
if err != nil {
return nil, err
}
return refreshJobFromDB(job), nil
}
// Claim 原子抢占订单刷新后台任务。
func (r storeOrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) {
return r.store.OrderRefreshJobs.Claim(ctx, id, token, leaseExpiresAt)
}
// Cancel 按用户归属委托订单刷新任务取消。
func (r storeOrderRepository) Cancel(ctx context.Context, userID int64, id string) (bool, error) {
return r.store.OrderRefreshJobs.Cancel(ctx, userID, id)
}
// Complete 以租约令牌安全写入订单刷新后台任务终态。
func (r storeOrderRepository) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) {
return r.store.OrderRefreshJobs.Complete(ctx, id, token, status, resultJSON, errorMessage)
}
// Recoverable 查询租约过期的订单刷新后台任务。
func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit int) ([]orderapp.RefreshJob, error) {
// jobs、err 保存数据库层可恢复任务及查询错误。
jobs, err := r.store.OrderRefreshJobs.Recoverable(ctx, now, limit)
if err != nil {
return nil, err
}
// converted 保存转换后的应用层任务列表。
converted := make([]orderapp.RefreshJob, 0, len(jobs))
for _, job := range jobs { // job 表示当前待转换的数据库任务。
converted = append(converted, *refreshJobFromDB(&job))
}
return converted, nil
}
// RequeueExpired 将过期订单刷新后台任务恢复为 queued。
func (r storeOrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) {
return r.store.OrderRefreshJobs.RequeueExpired(ctx, id, now)
}
// refreshJobFromDB 将数据库任务模型转换为应用层任务模型。
func refreshJobFromDB(job *db.OrderRefreshJob) *orderapp.RefreshJob {
if job == nil {
return nil
}
return &orderapp.RefreshJob{
ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus,
Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage,
WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt,
CreatedAt: job.CreatedAt, UpdatedAt: job.UpdatedAt,
}
}
// newStoreOrderRepository 从完整 Store 构造订单应用服务窄 repository。
func newStoreOrderRepository(store *db.Store) *storeOrderRepository {
if store == nil || store.Cookies == nil || store.Orders == nil || store.Items == nil {
return nil
}
return &storeOrderRepository{store: store}
}
// newStoreOrderRefreshJobRepository 构造订单刷新任务持久化适配器。
func newStoreOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository {
if store == nil || store.OrderRefreshJobs == nil {
return nil
}
return storeOrderRepository{store: store}
}
// 确保 Store 适配器始终覆盖订单应用服务所需的全部能力。
var _ orderapp.Repository = storeOrderRepository{}
var _ orderapp.UnitOfWork = storeOrderRepository{}
var _ orderapp.Writer = storeOrderWriter{}
var _ orderapp.RefreshJobRepository = storeOrderRepository{}
+102 -172
View File
@@ -3,81 +3,98 @@ package server
import (
"context"
"errors"
"strings"
"time"
"log/slog"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// serverOrderRuntimeAdapter 将 Server 的运行时能力适配为订单应用 Port。
// 适配器只存在于装配边界,订单应用服务本身不再依赖 *Server。
type serverOrderRuntimeAdapter struct {
// server 保存需要被适配的 Server 聚合对象。
server *Server
// runtime 保存已下沉到 adapter 包的订单运行时端口。
runtime *adapter.OrderRuntime
}
// newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。
func newServerOrderRuntime(server *Server) serverOrderRuntimeAdapter {
return serverOrderRuntimeAdapter{server: server}
func newServerOrderRuntime(server *Server, reconciliation orderapp.ReconciliationRecorder) serverOrderRuntimeAdapter {
// hooks 保存 Server 运行时回调,避免适配器反向依赖 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,
}
}
// logger 保存 Server 使用的日志器;适配器会在缺失时使用默认日志器。
var logger = (*slog.Logger)(nil)
if server != nil {
logger = server.Logger
}
// runtime 保存已完成数据库与 Server 回调装配的订单运行时;零值 Server 只用于测试缺失依赖分支。
var runtime *adapter.OrderRuntime
if server == nil {
runtime = adapter.NewOrderRuntime(nil, hooks, reconciliation, logger)
} else {
runtime = server.dependencies.NewOrderRuntime(hooks, reconciliation, logger)
}
return serverOrderRuntimeAdapter{runtime: runtime}
}
// AccountRunning 判断指定账号是否在线运行。
func (a serverOrderRuntimeAdapter) AccountRunning(cookieID string) bool {
if a.server == nil || a.server.Manager == nil {
return false
}
// running 表示账号是否已有运行中的实例。
_, running := a.server.Manager.GetInstance(cookieID)
return running
return a.runtime != nil && a.runtime.AccountRunning(cookieID)
}
// AutomationReady 判断完整发货自动化依赖是否已装配。
func (a serverOrderRuntimeAdapter) AutomationReady() bool {
return a.server != nil && a.server.Manager != nil && a.server.automation != nil
return a.runtime != nil && a.runtime.AutomationReady()
}
// ManualFullDelivery 执行完整自动化发货。
func (a serverOrderRuntimeAdapter) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) {
if a.server == nil || a.server.automation == nil {
return 0, errors.New("自动化中心未初始化")
if a.runtime == nil {
return 0, errors.New("订单运行时未初始化")
}
return a.server.automation.ManualFullDelivery(ctx, orderForAutomation(order))
return a.runtime.ManualFullDelivery(ctx, order)
}
// MTopAvailable 判断平台客户端是否已注入。
func (a serverOrderRuntimeAdapter) MTopAvailable() bool {
return a.server != nil && a.server.MTop != nil
}
// mtopClient 返回订单流程使用的平台客户端。
func (a serverOrderRuntimeAdapter) mtopClient() mtop.Client {
if a.server == nil {
return nil
}
return a.server.mtopClient()
}
// consignWithCurrentCookie 使用当前账号凭证确认发货。
func (a serverOrderRuntimeAdapter) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
return a.server.consignWithCurrentCookie(ctx, cookieID, orderID, userID)
return a.runtime != nil && a.runtime.MTopAvailable()
}
// ConfirmShipment 将 Server 的确认发货能力适配为应用层结果模型。
func (a serverOrderRuntimeAdapter) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult {
// ok、messages、runtimeCookie、runtimeCookieChanged、err 保存确认发货结果及凭证变化。
ok, messages, runtimeCookie, runtimeCookieChanged, err := a.consignWithCurrentCookie(ctx, cookieID, orderID, userID)
return orderapp.ConsignResult{
Success: ok, Messages: messages, RuntimeCookie: runtimeCookie,
RuntimeCookieChanged: runtimeCookieChanged, Err: err,
if a.runtime == nil {
return orderapp.ConsignResult{Err: errors.New("订单运行时未初始化")}
}
return a.runtime.ConfirmShipment(ctx, cookieID, orderID, userID)
}
// updateRunningCookie 同步运行时账号 Cookie。
func (a serverOrderRuntimeAdapter) updateRunningCookie(ctx context.Context, cookieID, value string) {
a.server.updateRunningCookie(ctx, cookieID, value)
if a.runtime != nil {
a.runtime.UpdateRunningCookie(ctx, cookieID, value)
}
}
// UpdateRunningCookie 将运行时账号 Cookie 能力暴露给手动发货应用 Port。
@@ -87,7 +104,9 @@ func (a serverOrderRuntimeAdapter) UpdateRunningCookie(ctx context.Context, cook
// notifyDelivery 发送发货结果通知。
func (a serverOrderRuntimeAdapter) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
a.server.notifyDelivery(cookieID, buyerID, itemID, chatID, message)
if a.runtime != nil {
a.runtime.NotifyDelivery(cookieID, buyerID, itemID, chatID, message)
}
}
// NotifyDelivery 将发货通知能力暴露给手动发货应用 Port。
@@ -97,10 +116,10 @@ func (a serverOrderRuntimeAdapter) NotifyDelivery(cookieID, buyerID, itemID, cha
// RecordOrderReconciliation 将外部动作成功后的本地状态异常写入补偿记录。
func (a serverOrderRuntimeAdapter) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
if a.server == nil || a.server.Store == nil || a.server.Store.Reconciliations == nil {
return "", errors.New("订单补偿存储未初始化")
if a.runtime == nil {
return "", errors.New("订单运行时未初始化")
}
return a.server.Store.Reconciliations.CreatePending(ctx, orderID, cookieID, kind, message)
return a.runtime.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。
@@ -110,127 +129,61 @@ func (a serverOrderRuntimeAdapter) RecordReconciliation(ctx context.Context, ord
// ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。
func (a serverOrderRuntimeAdapter) ReportPersistenceFailure(orderID string, err error) {
if a.server == nil || a.server.Logger == nil || err == nil {
return
if a.runtime != nil {
a.runtime.ReportPersistenceFailure(orderID, err)
}
a.server.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err)
}
// RecoverExpiredSession 处理订单刷新应用服务报告的平台会话过期。
func (a serverOrderRuntimeAdapter) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
return a.server.recoverExpiredMTOPSession(ctx, cookieID, err)
return a.runtime != nil && a.runtime.RecoverExpiredSession(ctx, cookieID, err)
}
// DetailAvailable 判断订单详情接口是否可用。
func (a serverOrderRuntimeAdapter) DetailAvailable() bool {
// ok 表示当前平台客户端是否实现详情接口。
_, ok := a.mtopClient().(orderDetailMTop)
return ok
return a.runtime != nil && a.runtime.DetailAvailable()
}
// SoldAvailable 判断已售订单列表接口是否可用。
func (a serverOrderRuntimeAdapter) SoldAvailable() bool {
// ok 表示当前平台客户端是否实现订单列表接口。
_, ok := a.mtopClient().(mtop.SoldOrderFetcher)
return ok
return a.runtime != nil && a.runtime.SoldAvailable()
}
// CredentialAvailable 判断平台请求视图是否包含可用 Cookie。
func (a serverOrderRuntimeAdapter) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool {
return detail != nil && strings.TrimSpace(detail.Value) != ""
return a.runtime != nil && a.runtime.CredentialAvailable(detail)
}
// FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。
func (a serverOrderRuntimeAdapter) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) {
// fetcher、ok 保存详情接口适配器及其实现状态。
fetcher, ok := a.mtopClient().(orderDetailMTop)
if !ok {
return orderapp.RefreshDetailFetchResult{}, orderapp.ErrRefreshDetailUnsupported
if a.runtime == nil {
return orderapp.RefreshDetailFetchResult{}, errors.New("订单运行时未初始化")
}
if detail == nil {
return orderapp.RefreshDetailFetchResult{}, errors.New("订单详情请求缺少账号凭证")
}
// requestCtx、session 保存带 Cookie 快照的请求上下文和会话。
requestCtx, session := withMTopCookieSnapshot(ctx, cookieDetailForOrderPlatform(detail))
// result、err 保存平台详情响应及错误。
result, err := fetcher.FetchOrderDetail(requestCtx, detail.Value, orderID)
if err != nil {
return orderapp.RefreshDetailFetchResult{CookieUpdate: a.refreshCookieUpdate(detail, session)}, err
}
if result == nil {
return orderapp.RefreshDetailFetchResult{CookieUpdate: a.refreshCookieUpdate(detail, session)}, errors.New("订单详情接口未返回结果")
}
return orderapp.RefreshDetailFetchResult{Detail: &orderapp.RefreshDetail{Quantity: result.Quantity, SpecName: result.SpecName, SpecValue: result.SpecValue, OrderStatus: result.OrderStatus, Amount: result.Amount, UpdatedCookies: result.UpdatedCookies}, CookieUpdate: a.refreshCookieUpdate(detail, session)}, nil
return a.runtime.FetchOrderDetail(ctx, detail, orderID)
}
// FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。
func (a serverOrderRuntimeAdapter) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) {
// fetcher、ok 保存订单列表接口适配器及其实现状态。
fetcher, ok := a.mtopClient().(mtop.SoldOrderFetcher)
if !ok {
return orderapp.RefreshSoldFetchResult{}, errors.New("当前 MTop 客户端不支持订单列表发现")
if a.runtime == nil {
return orderapp.RefreshSoldFetchResult{}, errors.New("订单运行时未初始化")
}
if detail == nil {
return orderapp.RefreshSoldFetchResult{}, errors.New("订单列表请求缺少账号凭证")
}
// requestCtx、session 保存带 Cookie 快照的请求上下文和会话。
requestCtx, session := withMTopCookieSnapshot(ctx, cookieDetailForOrderPlatform(detail))
// orders 保存跨分页累积的平台订单。
orders := make([]orderapp.RefreshSoldOrder, 0)
// pageNumber 是当前请求的订单列表页码。
for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
// page、err 保存当前订单列表页及错误。
page, err := fetcher.FetchSoldOrdersPage(requestCtx, detail.Value, pageNumber, 30)
if err != nil {
return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: a.refreshCookieUpdate(detail, session)}, err
}
// remote 是当前平台订单列表项。
for _, remote := range page.Items {
orders = append(orders, orderapp.RefreshSoldOrder{OrderID: remote.OrderID, ItemID: remote.ItemID, BuyerID: remote.BuyerID, OrderStatus: orderapp.NormalizeOrderStatus(remote.OrderStatus), Quantity: remote.Quantity, Amount: remote.Amount, ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone, ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity, IsBargain: remote.IsBargain})
}
if !page.NextPage || len(page.Items) == 0 {
break
}
}
return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: a.refreshCookieUpdate(detail, session)}, nil
}
// refreshCookieUpdate 将平台 CookieSession 转换为应用层 Cookie 更新模型。
func (a serverOrderRuntimeAdapter) refreshCookieUpdate(detail *orderapp.PlatformRuntimeData, session *mtop.CookieSession) orderapp.RefreshCookieUpdate {
if detail == nil || session == nil {
return orderapp.RefreshCookieUpdate{}
}
// value、snapshot、changed 保存会话当前 Cookie、快照和变化状态。
value, snapshot, changed := session.State()
if snapshot == nil {
return orderapp.RefreshCookieUpdate{Value: value, Changed: changed, Handled: false}
}
// metadata 保存包含完整 Cookie 快照的元数据。
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
return orderapp.RefreshCookieUpdate{Value: value, MetadataJSON: metadata, Changed: changed, Handled: true}
return a.runtime.FetchSoldOrders(ctx, detail)
}
// PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。
func (a serverOrderRuntimeAdapter) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) {
if detail == nil || !update.Handled {
return "", false, false, nil
if a.runtime == nil {
if detail == nil {
return update.Value, false, update.Handled, errors.New("订单运行时未初始化")
}
return update.Value, update.Value != detail.Value, update.Handled, errors.New("订单运行时未初始化")
}
if !update.Changed {
return detail.Value, false, true, nil
}
if a.server == nil || a.server.Store == nil || a.server.Store.Cookies == nil {
return update.Value, update.Value != detail.Value, true, errors.New("账号 Cookie 存储未初始化")
}
// err 保存账号续期 Cookie 写入错误。
if err := a.server.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, update.Value, update.MetadataJSON, time.Now().Unix()); err != nil {
return update.Value, update.Value != detail.Value, true, err
}
return update.Value, update.Value != detail.Value, true, nil
return a.runtime.PersistCookieSession(ctx, detail, update)
}
// IsSessionExpired 判断平台错误是否为会话过期。
func (a serverOrderRuntimeAdapter) IsSessionExpired(err error) bool {
return mtop.IsSessionExpiredErr(err)
return a.runtime != nil && a.runtime.IsSessionExpired(err)
}
// orderHTTPAdapter 将 HTTP 请求模型和兼容响应模型适配到应用层订单服务。
@@ -246,11 +199,12 @@ type orderHTTPAdapter struct {
func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderSingleRefreshResponse, error) {
// result、err 保存应用层单订单刷新结果和错误。
result, err := a.services.Refresh.RefreshSingle(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrNotFound) {
return orderSingleRefreshResponse{}, db.ErrNotFound
return orderSingleRefreshResponse{}, orderapp.ErrNotFound
}
if errors.Is(err, orderapp.ErrForbidden) {
return orderSingleRefreshResponse{}, db.ErrForbidden
return orderSingleRefreshResponse{}, orderapp.ErrForbidden
}
if errors.Is(err, orderapp.ErrRefreshDetailUnsupported) {
return orderSingleRefreshResponse{}, errOrderDetailUnsupported
@@ -268,8 +222,9 @@ func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orde
func (a *orderHTTPAdapter) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) {
// result、err 保存应用层批量刷新结果和错误。
result, err := a.services.Refresh.Refresh(ctx, userID, cookieID, status)
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return orderRefreshResponse{}, db.ErrForbidden
return orderRefreshResponse{}, orderapp.ErrForbidden
}
if err != nil {
return orderRefreshResponse{}, err
@@ -399,7 +354,7 @@ type orderListResult struct {
// orderDTOFromRow 把数据库订单列表行转换为稳定的订单响应视图。
func orderDTOFromRow(row orderapp.OrderRow) orderDTO {
// status 保存状态,供当前处理流程使用
status := db.NormalizeOrderStatus(row.OrderStatus)
status := orderapp.NormalizeOrderStatus(row.OrderStatus)
return orderDTO{
OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle,
ItemImage: itemImageFromDetail(row.ItemDetail), BuyerID: row.BuyerID,
@@ -421,7 +376,7 @@ func orderDTOFromOrder(order *orderapp.Order, item *orderapp.ItemInfo) orderDTO
itemImage = itemImageFromDetail(item.ItemDetail)
}
// status 保存状态,供当前处理流程使用
status := db.NormalizeOrderStatus(order.OrderStatus)
status := orderapp.NormalizeOrderStatus(order.OrderStatus)
return orderDTO{
OrderID: order.OrderID, ItemID: order.ItemID, ItemTitle: itemTitle, ItemImage: itemImage,
BuyerID: order.BuyerID, SpecName: order.SpecName, SpecValue: order.SpecValue,
@@ -433,36 +388,6 @@ func orderDTOFromOrder(order *orderapp.Order, item *orderapp.ItemInfo) orderDTO
}
}
// orderForAutomation 将订单应用实体转换为尚未迁移完成的自动化中心数据库实体。
func orderForAutomation(order *orderapp.Order) *db.Order {
if order == nil {
return nil
}
return &db.Order{
OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID,
SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity,
Amount: order.Amount, OrderStatus: order.OrderStatus, CookieID: order.CookieID,
IsBargain: order.IsBargain, ReceiverName: order.ReceiverName,
ReceiverPhone: order.ReceiverPhone, ReceiverAddr: order.ReceiverAddress,
ReceiverCity: order.ReceiverCity, Version: order.Version, ChatID: order.ChatID,
SystemShipped: order.SystemShipped, PaidAt: order.PaidAt, ShippedAt: order.ShippedAt,
CompletedAt: order.CompletedAt, BuyerReviewedAt: order.BuyerReviewedAt,
LastReviewRequestAt: order.LastReviewRequestAt, ReviewRequestCount: order.ReviewRequestCount,
CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt,
}
}
// cookieDetailForOrderPlatform 将订单应用层平台运行视图转换为共享 Server 会话辅助函数所需的兼容详情。
func cookieDetailForOrderPlatform(data *orderapp.PlatformRuntimeData) *db.CookieDetail {
if data == nil {
return nil
}
return &db.CookieDetail{
ID: data.ID, UserID: data.UserID, Value: data.Value,
MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser,
}
}
// orderDetailResult 返回订单详情的统一响应视图。
type orderDetailResult struct {
// Order 是已经完成商品信息补全的订单视图。
@@ -476,8 +401,9 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde
UserID: query.UserID, CookieID: query.CookieID, Status: query.Status,
Search: query.Search, Page: query.Page, PageSize: query.PageSize,
})
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return orderListResult{}, db.ErrForbidden
return orderListResult{}, orderapp.ErrForbidden
}
if err != nil {
return orderListResult{}, err
@@ -498,11 +424,12 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde
func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string) (*orderapp.Order, error) {
// order、err 保存应用层订单详情结果及错误。
order, err := a.services.Detail.Get(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrNotFound) {
return nil, db.ErrNotFound
return nil, orderapp.ErrNotFound
}
if errors.Is(err, orderapp.ErrForbidden) {
return nil, db.ErrForbidden
return nil, orderapp.ErrForbidden
}
return order, err
}
@@ -511,11 +438,12 @@ func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string
func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID string) (orderDetailResult, error) {
// result、err 保存应用层详情结果及错误。
result, err := a.services.Detail.GetView(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrNotFound) {
return orderDetailResult{}, db.ErrNotFound
return orderDetailResult{}, orderapp.ErrNotFound
}
if errors.Is(err, orderapp.ErrForbidden) {
return orderDetailResult{}, db.ErrForbidden
return orderDetailResult{}, orderapp.ErrForbidden
}
if err != nil {
return orderDetailResult{}, err
@@ -527,11 +455,12 @@ func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID st
func (a *orderHTTPAdapter) Delete(ctx context.Context, userID int64, orderID string) error {
// err 保存应用层订单删除错误。
err := a.services.Delete.Delete(ctx, userID, orderID)
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return db.ErrForbidden
return orderapp.ErrForbidden
}
if errors.Is(err, orderapp.ErrNotFound) {
return db.ErrNotFound
return orderapp.ErrNotFound
}
return err
}
@@ -586,11 +515,12 @@ func (a *orderHTTPAdapter) Update(ctx context.Context, userID int64, orderID str
if errors.As(err, &validationErr) {
return newOrderBadRequest(validationErr.Error())
}
err = adapter.NormalizeOrderError(err)
if errors.Is(err, orderapp.ErrForbidden) {
return db.ErrForbidden
return orderapp.ErrForbidden
}
if errors.Is(err, orderapp.ErrNotFound) {
return db.ErrNotFound
return orderapp.ErrNotFound
}
return err
}
@@ -0,0 +1,79 @@
package server
import (
"context"
"errors"
"testing"
orderapp "xianyu-go/internal/application/orders"
)
// serverOrderReconciliationRecorderFake 是 Server 订单运行时适配器测试使用的补偿 Port。
type serverOrderReconciliationRecorderFake struct {
// recordID 保存测试补偿写入成功时返回的记录标识。
recordID string
// recordErr 保存测试补偿写入失败时返回的错误。
recordErr error
// orderID、cookieID、kind、message 保存最近一次收到的业务字段。
orderID string
cookieID string
kind string
message string
}
// RecordReconciliation 记录 Server 适配器传入的补偿写入请求。
func (f *serverOrderReconciliationRecorderFake) RecordReconciliation(_ context.Context, orderID, cookieID, kind, message string) (string, error) {
f.orderID, f.cookieID, f.kind, f.message = orderID, cookieID, kind, message
return f.recordID, f.recordErr
}
// TestServerOrderRuntimeAdapterReconciliationPort 验证 Server 只通过订单应用 Port 转发补偿写入。
func TestServerOrderRuntimeAdapterReconciliationPort(t *testing.T) {
// expectedErr 保存底层补偿写入失败时应原样返回的错误。
expectedErr := errors.New("补偿数据库写入失败")
// testCases 保存补偿 Port 成功、缺失和持久化失败三种 Server 边界场景。
testCases := []struct {
// name 是当前边界场景的测试名称。
name string
// recorder 是当前场景注入的补偿应用 Port。
recorder *serverOrderReconciliationRecorderFake
// wantID 是当前场景预期返回的补偿记录标识。
wantID string
// wantErr 是当前场景预期返回的错误。
wantErr error
// wantErrText 是无法共享错误实例时用于校验的错误文本。
wantErrText string
}{
{name: "成功", recorder: &serverOrderReconciliationRecorderFake{recordID: "reconcile-1"}, wantID: "reconcile-1"},
{name: "缺失依赖", wantErrText: "订单补偿存储未初始化"},
{name: "持久化错误", recorder: &serverOrderReconciliationRecorderFake{recordErr: expectedErr}, wantErr: expectedErr},
}
// testCase 表示当前遍历的 Server 补偿边界场景。
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
// recorder 是避免把空指针伪装成非空接口的补偿应用 Port。
var recorder orderapp.ReconciliationRecorder
if testCase.recorder != nil {
recorder = testCase.recorder
}
// runtime 保存当前场景构造的 Server 订单运行时适配器。
runtime := newServerOrderRuntime(nil, recorder)
// recordID、recordErr 保存适配器转发后的补偿写入结果。
recordID, recordErr := runtime.RecordOrderReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "本地订单写入失败")
// errMatches 表示当前返回错误是否符合场景预期;缺失依赖场景只校验错误文本。
errMatches := recordErr == nil || testCase.wantErrText != ""
if testCase.wantErr != nil {
errMatches = errors.Is(recordErr, testCase.wantErr)
}
if testCase.wantErrText != "" {
errMatches = recordErr != nil && recordErr.Error() == testCase.wantErrText
}
if recordID != testCase.wantID || !errMatches {
t.Fatalf("补偿 Port 边界结果异常: id=%q err=%v wantID=%q wantErr=%v", recordID, recordErr, testCase.wantID, testCase.wantErr)
}
if testCase.recorder != nil && (testCase.recorder.orderID != "order-1" || testCase.recorder.cookieID != "cookie-1" || testCase.recorder.kind != "manual_status_ship" || testCase.recorder.message != "本地订单写入失败") {
t.Fatalf("补偿字段未完整转发: %+v", testCase.recorder)
}
})
}
}
+19 -72
View File
@@ -1,49 +1,39 @@
package server
import (
"errors"
"net/http"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// authSess 从请求上下文读取经过认证中间件注入的会话。
func authSess(r *http.Request) *auth.SessionIdentity {
return auth.IdentityFromContext(r.Context())
}
// requireCookieOwner 负责require登录凭证所有者相关处理。
func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) {
func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (accountapp.AccountSummary, bool) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return nil, false
return accountapp.AccountSummary{}, false
}
// d、err 保存d、err,供当前处理流程使用
d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cookieID)
if err != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return nil, false
return accountapp.AccountSummary{}, false
}
if d.UserID != sess.UserID {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return nil, false
return accountapp.AccountSummary{}, false
}
return d, true
}
// requireCookieSecretOwner 校验账号归属后读取登录设置所需的完整详情,仅供需要密码的管理流程使用。
func (s *Server) requireCookieSecretOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) {
// ownerOK 表示当前会话是否通过账号所有权校验。
_, ownerOK := s.requireCookieOwner(w, r, cookieID)
if !ownerOK {
return nil, false
}
// detail 是登录设置流程需要的用户名、密码和浏览器显示设置。
detail, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
if err != nil || detail == nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return nil, false
}
return detail, true
}
// requireCookieOwnership 校验当前会话是否拥有账号,只读取账号所有权元数据,不解密凭证。
func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request, cookieID string) bool {
// sess 是当前请求经过认证中间件注入的会话。
@@ -52,62 +42,19 @@ func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request,
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
// owned 表示当前用户是否直接拥有该账号。
owned, ownedErr := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, cookieID)
if ownedErr != nil {
// service 提供按用户过滤的非敏感所有权判断,避免 Server 直接访问账号表。
service := s.accountSummaryApplication()
if service == nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return false
}
if owned {
// ownershipErr 保存应用服务返回的账号归属结果。
if ownershipErr := service.RequireOwnership(r.Context(), sess.UserID, cookieID); ownershipErr == nil {
return true
}
// ownerID 用于区分账号不存在和账号属于其他用户,保持原有 404/403 响应语义。
ownerID, ownerErr := s.Store.Cookies.GetOwnerID(r.Context(), cookieID)
if ownerErr != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return false
}
if ownerID != sess.UserID {
} else if errors.Is(ownershipErr, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return false
}
return true
}
// requireCardOwner 校验当前会话是否拥有卡券组。
func (s *Server) requireCardOwner(w http.ResponseWriter, r *http.Request, cardID int64) (*db.CardFull, bool) {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return nil, false
}
// card 和 err 分别表示卡券组记录及其查询错误。
card, err := s.Store.Cards.Get(r.Context(), cardID)
if err != nil {
writeErr(w, http.StatusNotFound, "卡券不存在")
return nil, false
}
if card.UserID != sess.UserID {
writeErr(w, http.StatusForbidden, "无权操作该卡密组")
return nil, false
}
return card, true
}
// requireChannelOwner 校验当前会话是否拥有通知渠道。
func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, channelID int64) bool {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
// exists 和 err 表示通知渠道归属查询结果及错误。
exists, err := s.Store.Notifications.OwnsChannel(r.Context(), channelID, sess.UserID)
if err != nil || !exists {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return false
}
return true
writeErr(w, http.StatusNotFound, "账号不存在")
return false
}
@@ -0,0 +1,35 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// TestRequireCookieOwnerSkipsLoginSecret 验证账号所有权校验不依赖登录密码密文。
func TestRequireCookieOwnerSkipsLoginSecret(t *testing.T) {
// srv、store 和 cleanup 分别保存测试服务器、数据库和资源清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 是本测试共用的数据库上下文。
ctx := context.Background()
// _, updateErr 表示将登录密码替换为损坏密文的数据库操作结果;所有权摘要不应读取该字段。
if _, updateErr := store.DB.ExecContext(ctx,
`UPDATE cookies SET password=? WHERE id=?`, "not-a-password-ciphertext", "acc1"); updateErr != nil {
t.Fatalf("损坏登录密码密文失败: %v", updateErr)
}
// request 是携带默认测试用户会话的所有权请求。
request := httptest.NewRequest(http.MethodGet, "/cookies/acc1", nil)
request = request.WithContext(auth.WithSession(request.Context(), &db.Session{UserID: 1}))
// recorder 捕获所有权辅助函数可能写入的 HTTP 错误响应。
recorder := httptest.NewRecorder()
// detail、owned 表示所有权校验返回的非敏感应用摘要及校验结果。
detail, owned := srv.requireCookieOwner(recorder, request, "acc1")
if !owned || detail.ID != "acc1" || detail.UserID != 1 {
t.Fatalf("detail=%+v owned=%v status=%d body=%s", detail, owned, recorder.Code, recorder.Body.String())
}
}
+4 -39
View File
@@ -316,28 +316,10 @@ func TestPublishBatchHelpers(t *testing.T) {
}
}
// TestParsePublishCardActions 负责TestParse发布卡密动作列表相关处理。
func TestParsePublishCardActions(t *testing.T) {
// actions、parseErr 保存actions、parseErr,供当前处理流程使用
actions, parseErr := parsePublishCardActions("101:1:0; 102:2:3")
if parseErr != "" {
t.Fatalf("parsePublishCardActions: %s", parseErr)
}
if len(actions) != 2 {
t.Fatalf("actions=%+v", actions)
}
if actions[0].CardID != 101 || actions[0].DeliveryCount != 1 || actions[0].DelaySeconds != 0 {
t.Fatalf("actions[0]=%+v", actions[0])
}
if actions[1].CardID != 102 || actions[1].DeliveryCount != 2 || actions[1].DelaySeconds != 3 {
t.Fatalf("actions[1]=%+v", actions[1])
}
if // parseErr 保存parseErr,供当前处理流程使用
_, parseErr := parsePublishCardActions("101:0"); parseErr == "" {
t.Fatal("每件份数为0时应返回格式错误")
}
if // got 保存got,供当前处理流程使用
got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" {
// TestNormalizePublishCardHeader 验证批量发布卡密字段的历史表头兼容映射。
func TestNormalizePublishCardHeader(t *testing.T) {
// got 表示历史中文表头归一化后的字段名。
if got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" {
t.Fatalf("normalizePublishHeader=%q", got)
}
}
@@ -361,23 +343,6 @@ func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
}
}
// TestParsePublishAutomationSupportsMultipleCards 负责TestParse发布自动化SupportsMultiple卡密列表相关处理。
func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
// cfg 保存cfg,供当前处理流程使用
cfg := parsePublishAutomation(map[string]any{
"paid_delivery_enabled": "是",
"paid_delivery_contents": "101:1:0;102:2:0",
"review_gift_enabled": "true",
"review_gift_contents": "201:1",
})
if !cfg.PaidDelivery.Enabled || len(cfg.PaidDelivery.Actions) != 2 {
t.Fatalf("paid delivery=%+v", cfg.PaidDelivery)
}
if !cfg.ReviewGift.Enabled || len(cfg.ReviewGift.Actions) != 1 {
t.Fatalf("review gift=%+v", cfg.ReviewGift)
}
}
// TestPublicIPValidation 负责TestPublicIPValidation相关处理。
func TestPublicIPValidation(t *testing.T) {
// raw 表示当前遍历过程中的原始
+27 -34
View File
@@ -2,50 +2,43 @@ package server
import (
"context"
"errors"
"xianyu-go/internal/db"
accountapp "xianyu-go/internal/application/account"
)
// loadCookiePlatformDetail 读取平台请求所需的最小 Cookie 状态,并转换为 Server 内部已有的会话适配模型。
func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) {
// platformData 是 repository 返回的不含登录密码的平台运行视图。
platformData, err := s.Store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) (*accountapp.CredentialDetail, error) {
if s == nil {
return nil, errors.New("平台凭证读取服务未初始化")
}
// repository 提供不读取登录密码的平台凭证窄视图;SQL 和解密逻辑由 adapter 负责。
repository := s.accountLoginRepositoryForServer()
if repository == nil {
return nil, errors.New("平台凭证 repository 未初始化")
}
// platformData 是应用 Port 返回的不含登录密码的平台运行视图。
platformData, err := repository.LoadPlatformDetail(ctx, cookieID)
if err != nil {
return nil, err
}
// detail 是仅供 Cookie Session 适配器使用的浅层模型,不包含用户名、密码或账号设置。
detail := &db.CookieDetail{
ID: platformData.ID,
UserID: platformData.UserID,
Value: platformData.Value,
MetadataJSON: platformData.MetadataJSON,
}
return detail, nil
return platformData, nil
}
// loadCookieSummaryDetail 读取账号非敏感摘要并转换为 Server 内部的兼容模型。
func (s *Server) loadCookieSummaryDetail(ctx context.Context, userID int64, cookieID string) (*db.CookieDetail, error) {
// summary 是按当前用户与账号 ID 联合过滤得到的非敏感摘要。
summary, err := s.Store.Cookies.GetSummaryOwned(ctx, userID, cookieID)
if err != nil {
return nil, err
func (s *Server) loadCookieSummaryDetail(ctx context.Context, userID int64, cookieID string) (accountapp.AccountSummary, error) {
if s == nil {
return accountapp.AccountSummary{}, errors.New("账号摘要读取服务未初始化")
}
// detail 是只包含摘要字段的兼容模型,不携带任何 Cookie、metadata 或登录密码。
detail := &db.CookieDetail{
ID: summary.ID,
UserID: summary.UserID,
AutoConfirm: summary.AutoConfirm,
Remark: summary.Remark,
PauseDuration: summary.PauseDuration,
PausedUntil: summary.PausedUntil,
Username: summary.Username,
ShowBrowser: summary.ShowBrowser,
Nickname: summary.Nickname,
AvatarURL: summary.AvatarURL,
LastRefreshAt: summary.LastRefreshAt,
LoginMethod: summary.LoginMethod,
LastLoginAt: summary.LastLoginAt,
CreatedAt: summary.CreatedAt,
// service 提供按用户和账号联合过滤的非敏感摘要;Server 不直接访问账号表。
service := s.accountSummaryApplication()
if service == nil {
return accountapp.AccountSummary{}, errors.New("账号摘要服务未初始化")
}
return detail, nil
// summary、queryErr 保存应用服务返回的非敏感摘要及查询错误。
summary, queryErr := service.GetOwnedSummary(ctx, userID, cookieID)
if queryErr != nil {
return accountapp.AccountSummary{}, queryErr
}
return summary, nil
}
@@ -0,0 +1,36 @@
package server
import (
"context"
"testing"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
)
// TestLoadCookiePlatformDetailRequiresCredentialPort 验证平台运行时读取不会在缺少应用 Port 时直接访问 Store。
func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) {
// srv 是仅装配空账号登录服务的测试 Server,模拟凭证适配器缺失场景。
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
// loadErr 保存缺少凭证 Port 时的平台视图读取错误。
_, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid")
if loadErr == nil {
t.Fatal("缺少凭证 Port 时不应继续读取平台运行视图")
}
}
// TestPersistMTopCookieSessionRequiresCredentialPort 验证 MTOP Cookie 会话写回通过凭证 Port 而非直接访问 Store。
func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) {
// srv 是仅装配空账号登录服务的测试 Server,模拟写回适配器缺失场景。
srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}}
// detail 是不含登录密码的兼容平台凭证模型。
detail := &accountapp.CredentialDetail{ID: "cid", Value: "sid=old", MetadataJSON: "{}"}
// ctx、session 保存发生权威 Cookie 变化的 MTOP 会话。
ctx, session := adapter.WithFlatCookieSession(context.Background(), detail.Value)
session.ReplaceSnapshot([]adapter.BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}})
// value、changed、handled、persistErr 保存会话写回结果及其错误阶段。
_, changed, handled, persistErr := srv.persistMTopCookieSessionLocked(ctx, detail, session)
if !changed || !handled || persistErr == nil {
t.Fatalf("缺少凭证 Port 时应报告写回错误: changed=%v handled=%v err=%v", changed, handled, persistErr)
}
}
@@ -29,7 +29,7 @@ func TestServerPlatformRuntimeDetailSkipsLoginSecrets(t *testing.T) {
}
// summaryDetail 是 ownership 和资料刷新使用的非敏感摘要适配模型。
summaryDetail, summaryErr := srv.loadCookieSummaryDetail(ctx, ownerID, "acc1")
if summaryErr != nil || summaryDetail == nil || summaryDetail.ID != "acc1" || summaryDetail.UserID != ownerID {
if summaryErr != nil || summaryDetail.ID != "acc1" || summaryDetail.UserID != ownerID {
t.Fatalf("summary detail=%+v err=%v", summaryDetail, summaryErr)
}
}
+23 -9
View File
@@ -15,6 +15,8 @@ import (
"testing"
"time"
"xianyu-go/internal/adapter"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
@@ -28,12 +30,12 @@ func TestFinalPublishBatchStatus(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in db.ItemPublishBatch
in itemapp.BatchInfo
want string
}{
{name: "completed", in: db.ItemPublishBatch{SuccessCount: 2}, want: "completed"},
{name: "failed", in: db.ItemPublishBatch{FailedCount: 2}, want: "failed"},
{name: "partially failed", in: db.ItemPublishBatch{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"},
{name: "completed", in: itemapp.BatchInfo{SuccessCount: 2}, want: "completed"},
{name: "failed", in: itemapp.BatchInfo{FailedCount: 2}, want: "failed"},
{name: "partially failed", in: itemapp.BatchInfo{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"},
}
// tt 表示当前遍历过程中的tt
for _, tt := range cases {
@@ -180,7 +182,7 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
}
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。
// 验证应用层批量 worker 把远端发布失败的行标记为 failed。
// TestRunItemPublishBatch_FailureMarksRowFailed 负责Test运行商品发布批次FailureMarksRow失败相关处理。
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
@@ -546,8 +548,20 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
remoteCalls++
return nil, context.Canceled
}))
if // err 保存err,供当前处理流程使用
err := srv.publishBatchRow(ctx, admin.ID, client, rows[0], "worker-2"); err != nil {
// port 将测试平台客户端接入批量远端应用端口;已保存远端结果时不会再次发起平台请求。
port := adapter.NewItemBatchPublishPort(store, func() mtop.Client { return client }, srv.Logger, srv.updateRunningCookie, func(callCtx context.Context, cookieID string, callErr error) {
srv.recoverExpiredMTOPSession(callCtx, cookieID, callErr)
}, readBatchImageFile, downloadImageURL)
// localService 保存本地商品和批次成功检查点收口能力。
localService, serviceErr := srv.newBatchLocalPublishService()
if serviceErr != nil {
t.Fatal(serviceErr)
}
// 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")
if err != nil {
t.Fatalf("resume local persistence: %v", err)
}
if remoteCalls != 0 {
@@ -622,9 +636,9 @@ func TestCreatePublishAutomationRules(t *testing.T) {
// automationJSON 保存自动化JSON,供当前处理流程使用
automationJSON := `{"paid_delivery":{"enabled":true,"actions":[{"card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":23}]}}`
if // err 保存err,供当前处理流程使用
err := srv.createPublishAutomationRules(ctx, admin.ID, db.ItemPublishBatchRow{
err := srv.createPublishAutomationRules(ctx, admin.ID, itemapp.BatchRow{
CookieID: "acc1", Title: "商品A", AutomationJSON: automationJSON,
}, &mtop.PublishItemResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil {
}, &itemapp.BatchPublishResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil {
t.Fatal(err)
}
// rules、err 保存rules、err,供当前处理流程使用
+84
View File
@@ -654,6 +654,90 @@ func TestDownloadItemPublishBatchResultNotFound(t *testing.T) {
}
}
// TestDownloadItemPublishBatchResultExportsRows 验证批次结果下载通过应用服务读取并保持 CSV 兼容格式。
func TestDownloadItemPublishBatchResultExportsRows(t *testing.T) {
// srv、store、cleanup 保存 HTTP 测试服务器、数据库和清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存本测试共用的非取消上下文。
ctx := context.Background()
// admin 保存下载批次的当前用户。
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
if adminErr != nil {
t.Fatalf("读取测试管理员失败: %v", adminErr)
}
// batchID 保存本次结果下载批次标识。
batchID := "download-success"
// createErr 保存测试批次及明细写入结果。
createErr := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: batchID, UserID: admin.ID, Filename: "items.csv", Status: "completed",
}, []db.ItemPublishBatchRow{{
RowNo: 2, CookieID: "acc1", Title: "商品A", Price: "12.50", Quantity: 3,
CategoryJSON: `{"cat_id":"5001","cat_name":"虚拟商品"}`, Status: "completed",
ItemID: "item-1", ItemURL: "https://example/item-1",
}})
if createErr != nil {
t.Fatalf("创建下载测试批次失败: %v", createErr)
}
// h 保存带应用服务装配的 HTTP 路由。
h := srv.Router()
// cookie 保存管理员登录会话。
cookie := loginHelper(t, h)
// req 保存结果下载请求。
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID+"/result.csv", nil)
req.AddCookie(cookie)
// rec 保存结果下载响应。
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("下载结果状态=%d body=%s", rec.Code, rec.Body.String())
}
// body 保存导出的 CSV 内容,包含 UTF-8 BOM、表头和业务明细。
body := rec.Body.String()
if !strings.HasPrefix(body, "\xEF\xBB\xBF") || !strings.Contains(body, "行号") || !strings.Contains(body, "商品A") || !strings.Contains(body, "item-1") {
t.Fatalf("导出 CSV 内容异常: %q", body)
}
}
// TestDownloadItemPublishBatchResultHidesOtherUserBatch 验证结果下载不会泄露其他用户的批次存在性。
func TestDownloadItemPublishBatchResultHidesOtherUserBatch(t *testing.T) {
// srv、store、cleanup 保存 HTTP 测试服务器、数据库和清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存本测试共用的非取消上下文。
ctx := context.Background()
// created 保存其他用户创建结果。
created, createUserErr := store.Users.Create(ctx, "download-other", "[email protected]", "pw")
if createUserErr != nil || !created {
t.Fatalf("创建其他用户失败: created=%v err=%v", created, createUserErr)
}
// other 保存其他用户的数据库身份。
other, otherErr := store.Users.GetByUsername(ctx, "download-other")
if otherErr != nil {
t.Fatalf("读取其他用户失败: %v", otherErr)
}
// createBatchErr 保存其他用户批次写入结果。
createBatchErr := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: "download-other-batch", UserID: other.ID, Filename: "items.csv", Status: "completed",
}, []db.ItemPublishBatchRow{{RowNo: 2, Title: "不应泄露", Status: "completed"}})
if createBatchErr != nil {
t.Fatalf("创建其他用户批次失败: %v", createBatchErr)
}
// h 保存结果下载路由。
h := srv.Router()
// cookie 保存当前管理员的登录会话。
cookie := loginHelper(t, h)
// req 保存越权结果下载请求。
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/download-other-batch/result.csv", nil)
req.AddCookie(cookie)
// rec 保存越权响应。
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("越权下载应隐藏批次并返回 404,got %d body=%s", rec.Code, rec.Body.String())
}
}
// TestSafeCSVCellPreventsSpreadsheetFormulaExecution 负责TestSafeCSVCellPreventsSpreadsheetFormulaExecution相关处理。
func TestSafeCSVCellPreventsSpreadsheetFormulaExecution(t *testing.T) {
// input 表示当前遍历过程中的input
-21
View File
@@ -10,7 +10,6 @@ import (
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/xianyu/cookierefresh"
)
// qrLoginGenerateTimeout 保存qr登录GenerateTimeout,供当前处理流程使用
@@ -298,23 +297,3 @@ func qrString(result map[string]any, key string) string {
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
// qrCookieSnapshot 负责qr登录凭证Snapshot相关处理。
func qrCookieSnapshot(result map[string]any) ([]cookierefresh.BrowserCookie, bool) {
// raw、ok 保存raw、ok,供当前处理流程使用
raw, ok := result["cookie_snapshot"]
if !ok {
return nil, false
}
// snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := raw.([]cookierefresh.BrowserCookie)
if !ok || snapshot == nil {
return nil, false
}
// normalized 保存normalized,供当前处理流程使用
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
return normalized, true
}
+2 -1
View File
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"xianyu-go/internal/adapter"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
)
@@ -285,7 +286,7 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
},
}}
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
snapshot, ok := adapter.CookieSnapshotsFromResult(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
}
ownQRSession(t, srv, store, "s1")
+15 -5
View File
@@ -7,6 +7,9 @@ import (
"net/http"
"testing"
"time"
"xianyu-go/internal/adapter"
"xianyu-go/internal/auth"
)
// freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。
@@ -122,18 +125,25 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
// TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。
func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
// err 是缺少 Store 时的构造校验错误。
if _, err := New(nil, nil, false, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少 db.Store 时应返回构造错误")
// err 是缺少基础设施容器时的构造校验错误。
if _, err := New(nil, nil, nil, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少基础设施容器时应返回构造错误")
}
// srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
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(srv.Store, nil, false, "", ":0", nil, nil, nil); err == nil {
if _, err := New(dependencies, authentication, nil, "", ":0", nil, nil, nil); err == nil {
t.Fatal("缺少 account.Manager 时应返回构造错误")
}
}
+122 -77
View File
@@ -1,5 +1,5 @@
// Package server 实现 HTTP API 服务(chi 路由)。
// 复用 internal/auth 中间件、internal/db.Store、internal/account.Manager。
// 复用 internal/auth 中间件、adapter 装配依赖和 internal/account.Manager。
// 端点按分组组织在同一 package 的多个 handler 文件中。
package server
@@ -20,26 +20,19 @@ import (
"github.com/go-chi/chi/v5/middleware"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/logging"
"xianyu-go/internal/notify"
"xianyu-go/internal/reconciliation"
appversion "xianyu-go/internal/version"
"xianyu-go/internal/webui"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/qrlogin"
xrenew "xianyu-go/internal/xianyu/renew"
)
// qrLoginService 保存qr登录Service,供当前处理流程使用
type qrLoginService interface {
GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error)
GetSessionStatus(sessionID string) map[string]any
CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error)
}
type qrLoginService = adapter.QRLoginService
// qrLoginPersistence 保存qr登录Persistence,供当前处理流程使用
type qrLoginPersistence struct {
@@ -64,33 +57,37 @@ type publishBatchWorker struct {
// ServerOption 是 Server 构造阶段应用可选依赖的配置函数。
type ServerOption func(*Server)
// databaseHealth 定义健康检查需要的最小数据库连通性能力。
type databaseHealth interface {
// Ping 在调用方 Context 内探测数据库连接是否可用。
Ping(context.Context) error
}
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
// Server 保存Server,供当前处理流程使用
type Server struct {
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
notifier *notify.Notifier
chat *chat.Service
MTop mtop.Client
CookieRenew xrenew.Service
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
// 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
// applications 保存统一装配的应用服务实例。
applications *applicationServices
// reconciliation 负责恢复外部发货成功但本地订单状态未完成的记录。
reconciliation *reconciliation.Service
// transactionRepository 提供统一事务执行所需的最小持久化能力。
transactionRepository transactionRepository
// itemSpecCacheMu 保护商品多规格探测缓存。
itemSpecCacheMu sync.Mutex
// itemSpecCache 保存短期商品多规格探测结果,减少重复远端请求。
itemSpecCache map[string]itemSpecCacheEntry
transactionRepository *adapter.TransactionRepository
// databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。
databaseHealth databaseHealth
publishMu sync.Mutex
publishCancels map[string]publishBatchWorker
orderRefreshMu sync.Mutex
@@ -98,7 +95,10 @@ type Server struct {
workerMu sync.Mutex
workerCount int
workersDone chan struct{}
backgroundWG sync.WaitGroup
// backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。
backgroundMu sync.Mutex
backgroundCount int
backgroundDone chan struct{}
// taskRegistryMu 保护后台任务注册表的惰性初始化,避免测试构造的零值 Server 产生数据竞争。
taskRegistryMu sync.Mutex
// taskRegistry 保存 Server 自有后台任务的生命周期状态,不持久化业务数据或敏感凭证。
@@ -133,9 +133,12 @@ func WithChatService(service *chat.Service) ServerOption {
// New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入
// (创建顺序:adapter → manager → automation → notifier → server)。
// New 负责New相关处理。
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
if store == nil {
return nil, fmt.Errorf("server 依赖 db.Store 不能为空")
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 依赖基础设施容器不能为空")
}
if authentication == nil {
return nil, fmt.Errorf("server 依赖认证服务不能为空")
}
if manager == nil {
return nil, fmt.Errorf("server 依赖 account.Manager 不能为空")
@@ -143,21 +146,19 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
if logger == nil {
logger = logging.NewLogger(os.Stdout, "text")
}
// qrMgr 是二维码登录流程使用的默认会话管理器。
qrMgr := qrlogin.NewManager(logger)
// server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。
server := &Server{
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
notifier: notifier,
MTop: mtop.NewClient(),
CookieRenew: xrenew.Service{},
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
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),
@@ -166,8 +167,8 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
qrPersisted: make(map[string]qrLoginPersistence),
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
itemSpecCache: make(map[string]itemSpecCacheEntry),
taskRegistry: newTaskRegistry(),
backgroundDone: closedSignal(),
}
// option 表示当前遍历过程中的option
for _, option := range options {
@@ -177,24 +178,25 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
}
}
server.applications = newApplicationServices(server)
server.transactionRepository = newStoreTransactionRepository(store)
server.reconciliation = reconciliation.New(store, logger)
server.transactionRepository = dependencies.NewTransactionRepository()
server.databaseHealth = dependencies.NewDatabaseHealth()
server.reconciliation = dependencies.NewReconciliationService(logger)
return server, nil
}
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
func (s *Server) mtopClient() mtop.Client {
func (s *Server) mtopClient() adapter.MTOPClient {
if s.MTop != nil {
return s.MTop
}
return mtop.NewClient()
return adapter.NewMTOPClient()
}
// recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。
// 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。
// recoverExpiredMTOPSession 负责recoverExpiredMTOP会话相关处理。
func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool {
if !mtop.IsSessionExpiredErr(err) {
if !adapter.IsSessionExpiredError(err) {
return false
}
if s.Logger != nil {
@@ -442,7 +444,7 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if s.Store == nil || s.Store.DB == nil || s.Store.DB.PingContext(ctx) != nil {
if s.databaseHealth == nil || s.databaseHealth.Ping(ctx) != nil {
writeJSON(w, http.StatusServiceUnavailable, healthResponse{Status: "degraded", Database: "unavailable"})
return
}
@@ -566,7 +568,7 @@ func (s *Server) Stop(ctx context.Context) error {
if httpDone != nil && !waitForSignal(ctx, httpDone) {
return ctx.Err()
}
if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) {
if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) {
return ctx.Err()
}
return nil
@@ -594,7 +596,7 @@ func (s *Server) Stop(ctx context.Context) error {
if httpDone != nil && !waitForSignal(ctx, httpDone) {
return ctx.Err()
}
if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) {
if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) {
return ctx.Err()
}
return shutdownErr
@@ -614,7 +616,7 @@ func (s *Server) WaitForBackground() {
if s == nil {
return
}
s.backgroundWG.Wait()
_ = s.waitForBackgroundContext(context.Background())
s.waitForWorkers(10 * time.Second)
}
@@ -633,34 +635,88 @@ func (s *Server) lifecycleContext() context.Context {
return s.lifecycleCtx
}
// startBackgroundTask 登记并启动一个受 Server 生命周期管理的后台任务。
// 调用方负责在任务函数内部响应上下文取消;WaitForBackground 会等待任务退出。
// startBackgroundTask 负责开始Background任务相关处理。
func (s *Server) startBackgroundTask(name string, task func()) string {
return s.startBackgroundTaskContext(name, s.lifecycleContext(), task)
}
// startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。
// 返回值是可供管理端查询的任务 ID;任务完成、取消或超时后会保留有限历史。
func (s *Server) startBackgroundTaskContext(name string, ctx context.Context, task func()) string {
return s.startBackgroundTaskResult(name, ctx, func() error {
if task != nil {
task()
}
return nil
})
}
// startBackgroundTaskResult 登记并启动可返回错误的 Server 后台任务。
// 任务错误会进入任务注册表;调用方仍需自行处理敏感错误日志和取消语义。
func (s *Server) startBackgroundTaskResult(name string, ctx context.Context, task func() error) string {
// taskID、complete 记录任务状态并提供一次性收束回调。
taskID, complete := s.taskRegistryForServer().start(name, ctx)
s.backgroundWG.Add(1)
s.beginBackgroundTask()
// #nosec G118 -- 任务由调用方提供的 Server 生命周期控制。
go func() {
defer s.backgroundWG.Done()
defer complete(nil)
defer s.finishBackgroundTask()
// taskErr 保存后台任务函数返回的可观测错误。
var taskErr error
defer func() { complete(taskErr) }()
if task == nil {
if s.Logger != nil {
s.Logger.Warn("跳过空后台任务", "task", name)
}
return
}
task()
taskErr = task()
}()
return taskID
}
// beginBackgroundTask 登记一个由 Server 负责等待的后台任务,并刷新零到一任务转换信号。
func (s *Server) beginBackgroundTask() {
if s == nil {
return
}
s.backgroundMu.Lock()
defer s.backgroundMu.Unlock()
if s.backgroundCount == 0 {
s.backgroundDone = make(chan struct{})
}
s.backgroundCount++
}
// finishBackgroundTask 标记一个后台任务退出,并在计数归零时关闭完成信号。
func (s *Server) finishBackgroundTask() {
if s == nil {
return
}
s.backgroundMu.Lock()
defer s.backgroundMu.Unlock()
if s.backgroundCount <= 0 {
return
}
s.backgroundCount--
if s.backgroundCount == 0 && s.backgroundDone != nil {
close(s.backgroundDone)
}
}
// waitForBackgroundContext 等待已登记后台任务退出;超时只结束当前等待,不创建游离等待 goroutine。
func (s *Server) waitForBackgroundContext(ctx context.Context) bool {
if s == nil {
return true
}
if ctx == nil {
ctx = context.Background()
}
s.backgroundMu.Lock()
// done 是当前后台任务批次归零时关闭的完成信号。
done := s.backgroundDone
if done == nil {
done = closedSignal()
s.backgroundDone = done
}
s.backgroundMu.Unlock()
return waitForSignal(ctx, done)
}
// StartOrderReconciliationRecovery 启动受 Server 生命周期管理的订单补偿扫描器。
func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) string {
if s == nil || s.reconciliation == nil {
@@ -745,14 +801,3 @@ func waitForSignal(ctx context.Context, signal <-chan struct{}) bool {
return false
}
}
// waitForWaitGroup 在关闭上下文取消或 WaitGroup 清空时返回,避免无界阻塞。
func waitForWaitGroup(ctx context.Context, group *sync.WaitGroup) bool {
// done 是 WaitGroup 清空后的完成信号。
done := make(chan struct{})
go func() {
group.Wait()
close(done)
}()
return waitForSignal(ctx, done)
}
+20 -2
View File
@@ -11,6 +11,8 @@ import (
"testing"
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
"xianyu-go/internal/db"
@@ -36,7 +38,15 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
// mgr 是使用空处理器的测试账号管理器。
mgr := account.NewManager(store, noopHandler{}, nil)
// srv 是未启用聊天服务的基础测试 HTTP 服务。
srv, err := New(store, mgr, false, "", ":0", nil, nil, nil)
// dependencies 保存测试 Server 使用的基础设施工厂,避免 Server 直接持有 Store。
dependencies, dependencyErr := adapter.NewDependencies(store)
if dependencyErr != nil {
t.Fatalf("NewDependencies: %v", dependencyErr)
}
// authentication 保存测试 HTTP 会话中间件需要的认证服务。
authentication := &auth.Service{Store: store}
// srv、err 保存测试 HTTP 服务构造结果及失败原因。
srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil)
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -85,7 +95,15 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
// mgr 是未初始化测试使用的空处理器账号管理器。
mgr := account.NewManager(store, noopHandler{}, nil)
// srv 是未初始化测试使用的 HTTP 服务实例。
srv, err := New(store, mgr, false, "", ":0", nil, nil, nil)
// dependencies 保存未初始化测试 Server 使用的基础设施工厂。
dependencies, dependencyErr := adapter.NewDependencies(store)
if dependencyErr != nil {
t.Fatalf("NewDependencies: %v", dependencyErr)
}
// authentication 保存未初始化数据库上的会话中间件依赖。
authentication := &auth.Service{Store: store}
// srv、err 保存未初始化测试服务构造结果及失败原因。
srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil)
if err != nil {
t.Fatalf("New: %v", err)
}
+10 -10
View File
@@ -96,7 +96,7 @@ func TestListAIModelsBadJSON(t *testing.T) {
// TestListAIModelsEmptyBaseURL 空地址使用默认并失败(默认阿里云地址不可达或返回非 2xx)。
func TestListAIModelsEmptyBaseURL(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// 注入一个返回错误状态码的本地 server。
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -104,7 +104,7 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) {
}))
defer ts.Close()
// 设置系统设置 ai_api_url 指向该 server。
srv.Store.Settings.Set(context.Background(), "ai_api_url", ts.URL)
store.Settings.Set(context.Background(), "ai_api_url", ts.URL)
// h 保存h,供当前处理流程使用
h := srv.Router()
@@ -150,7 +150,7 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
defer logging.Level.Set(slog.LevelInfo)
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
@@ -181,7 +181,7 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
t.Fatalf("runtime log level=%v want debug", got)
}
// saved、err 保存saved、err,供当前处理流程使用
saved, err := srv.Store.Settings.Get(context.Background(), "log_level")
saved, err := store.Settings.Get(context.Background(), "log_level")
if err != nil || saved != "debug" {
t.Fatalf("saved log_level=%q err=%v", saved, err)
}
@@ -190,12 +190,12 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
// TestSystemSettingsRequireAdmin 负责Test系统设置RequireAdmin相关处理。
func TestSystemSettingsRequireAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
if // err 保存err,供当前处理流程使用
_, err := srv.Store.Users.Create(context.Background(), "user-settings", "[email protected]", "pw"); err != nil {
_, err := store.Users.Create(context.Background(), "user-settings", "[email protected]", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
@@ -237,7 +237,7 @@ func TestSystemSettingsRequireAdmin(t *testing.T) {
// TestBulkSystemSettingsAreAtomic 负责TestBulk系统设置AreAtomic相关处理。
func TestBulkSystemSettingsAreAtomic(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
h := srv.Router()
@@ -254,7 +254,7 @@ func TestBulkSystemSettingsAreAtomic(t *testing.T) {
t.Fatalf("status=%d body=%s", badRec.Code, badRec.Body.String())
}
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value == "red" {
value, _ := store.Settings.Get(context.Background(), "theme_color"); value == "red" {
t.Fatal("invalid bulk request partially saved theme_color")
}
@@ -268,11 +268,11 @@ func TestBulkSystemSettingsAreAtomic(t *testing.T) {
t.Fatalf("status=%d body=%s", goodRec.Code, goodRec.Body.String())
}
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value != "blue" {
value, _ := store.Settings.Get(context.Background(), "theme_color"); value != "blue" {
t.Fatalf("theme_color=%q", value)
}
if // value 保存值,供当前处理流程使用
value, _ := srv.Store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" {
value, _ := store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" {
t.Fatalf("retention=%q", value)
}
}
+88 -272
View File
@@ -1,27 +1,19 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strings"
"time"
"github.com/go-chi/chi/v5"
settingsapp "xianyu-go/internal/application/settings"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/logging"
"xianyu-go/internal/netguard"
)
// maxOpenAIModelsResponseBytes 保存maxOpenAI模型列表响应Bytes,供当前处理流程使用
const maxOpenAIModelsResponseBytes = 4 << 20
// systemSettingSecretChangeRequest 是 HTTP 层接收的敏感设置变更命令。
type systemSettingSecretChangeRequest struct {
// Action 是 retain、replace 或 clear。
@@ -30,11 +22,6 @@ type systemSettingSecretChangeRequest struct {
Value string `json:"value,omitempty"`
}
// authSess 从上下文取会话。
func authSess(r *http.Request) *db.Session {
return auth.SessionFromContext(r.Context())
}
// mountSettingsReal 系统设置端点(管理员专用)。public 单独挂载在顶层。
func (s *Server) mountSettingsReal(r chi.Router) {
r.Group(func(r chi.Router) {
@@ -58,7 +45,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
// values 保存普通设置值。
values := make(map[string]string, len(raw))
// secrets 保存敏感设置的显式变更命令。
secrets := make(map[string]db.SensitiveSettingChange)
secrets := make(map[string]settingsapp.SecretChange)
// valuesRaw 是普通设置对象的原始 JSON;ok 表示请求是否包含该对象。
if valuesRaw, ok := raw["values"]; ok {
// explicitValues 是显式请求中的普通设置字段。
@@ -70,13 +57,13 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
}
// key 是显式普通设置中的字段名。
for key := range explicitValues {
if db.IsSensitiveSettingKey(key) {
if s.settingsApplication().IsSensitiveSettingKey(key) {
writeErr(w, http.StatusBadRequest, "敏感设置必须放入 secrets 命令")
return
}
}
// err 是普通设置字段校验错误。
if err := collectSystemSettingValues(explicitValues, values); err != nil {
if err := collectSystemSettingValues(explicitValues, values, s.settingsApplication().IsSensitiveSettingKey); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
@@ -93,11 +80,11 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
// key 是敏感设置键;change 是对应的三态命令。
for key, change := range explicitSecrets {
key = strings.TrimSpace(key)
if !db.IsSensitiveSettingKey(key) || !validSecretSettingAction(change.Action) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" {
if !s.settingsApplication().IsSensitiveSettingKey(key) || !validSecretSettingAction(change.Action) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" {
writeErr(w, http.StatusBadRequest, "敏感设置命令无效")
return
}
secrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value}
secrets[key] = settingsapp.SecretChange{Action: change.Action, Value: change.Value}
}
}
// legacy 保存旧版顶层普通设置字段,确保兼容接口可以渐进迁移。
@@ -105,7 +92,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
// key 是兼容顶层字段名;value 是其原始 JSON 值。
for key, value := range raw {
if key != "values" && key != "secrets" {
if db.IsSensitiveSettingKey(key) {
if s.settingsApplication().IsSensitiveSettingKey(key) {
writeErr(w, http.StatusBadRequest, "敏感设置必须放入 secrets 命令")
return
}
@@ -113,7 +100,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
}
}
// err 是兼容顶层字段校验错误。
if err := collectSystemSettingValues(legacy, values); err != nil {
if err := collectSystemSettingValues(legacy, values, s.settingsApplication().IsSensitiveSettingKey); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
@@ -126,27 +113,14 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if len(secrets) > 0 {
// sess 保存当前管理员会话,用于敏感设置写入审计。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// secretKeys 保存本次敏感设置写入涉及的键名。
secretKeys := make([]string, 0, len(secrets))
// key 是本次敏感设置写入涉及的键名。
for key := range secrets {
secretKeys = append(secretKeys, key)
}
// err 保存敏感设置写入审计错误。
if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.write", "system_settings", secretKeys); err != nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// sess 保存当前管理员会话,用于应用服务执行用户范围校验和敏感写入审计。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// err 是普通设置与敏感命令原子保存错误。
if err := s.Store.Settings.ApplyChanges(r.Context(), values, secrets); err != nil {
if err := s.settingsApplication().ApplySystemChanges(r.Context(), sess.UserID, values, secrets); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -158,14 +132,14 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
}
// collectSystemSettingValues 解析普通设置字段并拒绝敏感明文。
func collectSystemSettingValues(raw map[string]json.RawMessage, values map[string]string) error {
func collectSystemSettingValues(raw map[string]json.RawMessage, values map[string]string, isSensitive func(string) bool) error {
// key 是当前设置键;rawValue 是尚未转换的 JSON 值。
for key, rawValue := range raw {
key = strings.TrimSpace(key)
if key == "" || len(key) > 100 {
return errors.New("设置键无效")
}
if db.IsSensitiveSettingKey(key) {
if isSensitive(key) {
return fmt.Errorf("敏感设置 %q 必须使用 secrets 命令", key)
}
// value 是普通设置转换后的任意 JSON 值。
@@ -200,39 +174,10 @@ func validSecretSettingAction(action string) bool {
}
}
// auditSensitiveSettingsAccess 记录敏感设置访问动作,审计内容只包含键名而不包含秘密值。
func (s *Server) auditSensitiveSettingsAccess(ctx context.Context, userID int64, action, resource string, keys []string) error {
if len(keys) == 0 {
return nil
}
if s == nil || s.Store == nil || s.Store.SecurityAudit == nil {
return errors.New("敏感访问审计未初始化")
}
// normalizedKeys 保存排序去重后的敏感设置键名。
normalizedKeys := make([]string, 0, len(keys))
// seenKeys 保存已经加入审计记录的键名。
seenKeys := make(map[string]struct{}, len(keys))
// key 是当前待写入审计记录的敏感设置键名。
for _, key := range keys {
key = strings.TrimSpace(key)
if key == "" {
continue
}
// exists 表示敏感设置键名是否已经加入审计记录。
if _, exists := seenKeys[key]; exists {
continue
}
seenKeys[key] = struct{}{}
normalizedKeys = append(normalizedKeys, key)
}
sort.Strings(normalizedKeys)
return s.Store.SecurityAudit.Add(ctx, db.SecurityAuditLog{UserID: userID, Action: action, Resource: resource, Keys: normalizedKeys, Outcome: "accepted"})
}
// publicSettings 负责public设置相关处理。
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
// m、err 保存m、err,供当前处理流程使用
m, err := s.Store.Settings.Public(r.Context())
m, err := s.settingsApplication().PublicSystem(r.Context())
if err != nil {
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
return
@@ -242,19 +187,14 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
// allSettings 负责all设置相关处理。
func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
// sess 保存当前管理员会话,用于敏感配置读取审计。
// sess 保存当前管理员会话,用于应用服务执行敏感配置读取审计。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// err 保存敏感配置读取审计错误。
if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.read", "system_settings", db.SensitiveSettingKeys()); err != nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// m、err 保存m、err,供当前处理流程使用
m, err := s.Store.Settings.Redacted(r.Context())
// m、err 保存脱敏设置及应用服务查询错误。
m, err := s.settingsApplication().GetSystem(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -278,26 +218,21 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if db.IsSensitiveSettingKey(key) {
if s.settingsApplication().IsSensitiveSettingKey(key) {
// action 是最终采用的敏感设置命令。
action := req.Action
if !validSecretSettingAction(action) {
writeErr(w, http.StatusBadRequest, "敏感设置命令无效")
return
}
// sess 保存当前管理员会话,用于单项敏感设置写入审计。
// sess 保存当前管理员会话,用于应用服务执行单项敏感设置写入审计。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// err 保存单项敏感设置写入审计错误。
if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.write", "system_settings", []string{key}); err != nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// err 是单项敏感设置原子保存错误。
if err := s.Store.Settings.ApplyChanges(r.Context(), nil, map[string]db.SensitiveSettingChange{key: {Action: action, Value: req.Value}}); err != nil {
// err 是单项敏感设置原子保存或审计错误。
if err := s.settingsApplication().SetSystem(r.Context(), sess.UserID, key, req.Value, action); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -311,8 +246,14 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
return
}
}
if // err 保存err,供当前处理流程使用
err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil {
// sess 保存当前管理员会话,用于应用服务执行普通设置写入。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
// err 表示普通设置保存或应用服务校验失败。
if err := s.settingsApplication().SetSystem(r.Context(), sess.UserID, key, req.Value, ""); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -330,10 +271,10 @@ func (s *Server) mountAIReplyReal(r chi.Router) {
// listAIReply 负责listAI回复相关处理。
func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.Store.AIReply.ListForUser(r.Context(), sess.UserID)
// rows、err 保存应用层 AI 设置摘要及查询错误。
rows, err := s.settingsApplication().ListAIReply(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -358,23 +299,24 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
// sess 保存当前认证会话,用于应用服务执行账号归属校验。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// cfg、err 保存cfg、err,供当前处理流程使用
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
cfg, err := s.settingsApplication().GetAIReply(r.Context(), sess.UserID, cid)
if err != nil {
if !errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusInternalServerError, "查询失败")
if errors.Is(err, settingsapp.ErrConfigNotFound) {
// 未保存配置使用与旧接口一致的默认值。
writeJSON(w, http.StatusOK, aiReplySettingsResponse{AIEnabled: false, MaxDiscountPercent: 10, MaxDiscountAmount: 100, MaxBargainRounds: 3, CustomPrompts: ""})
return
}
// 未保存配置使用与旧接口一致的默认值。
// 默认响应不携带 cookie_id,避免误认为已持久化账号配置。
// max_discount_percent 保持默认 10 的业务约束。
// max_discount_amount 保持默认 100 的业务约束。
// max_bargain_rounds 保持默认 3 的业务约束。
// custom_prompts 为空表示未配置自定义提示词。
writeJSON(w, http.StatusOK, aiReplySettingsResponse{AIEnabled: false, MaxDiscountPercent: 10, MaxDiscountAmount: 100, MaxBargainRounds: 3, CustomPrompts: ""})
if writeSettingsAccountError(w, err) {
return
}
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// 已保存配置返回账号标识,客户端可据此区分账号级设置。
@@ -404,7 +346,18 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if !s.requireCookieOwnership(w, r, cid) {
// sess 保存当前认证会话,用于在字段校验前复用旧接口的账号归属错误优先级。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// ownershipErr 保存账号不存在、跨用户或数据库归属查询失败的结果;未配置 AI 设置不是账号错误。
if _, ownershipErr := s.settingsApplication().GetAIReply(r.Context(), sess.UserID, cid); ownershipErr != nil && !errors.Is(ownershipErr, settingsapp.ErrConfigNotFound) {
if writeSettingsAccountError(w, ownershipErr) {
return
}
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
if req.MaxDiscountPercent < 0 || req.MaxDiscountPercent > 100 {
@@ -420,21 +373,37 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
return
}
// err 是 AI 回复配置写入错误。
err := s.Store.AIReply.UpsertSettings(r.Context(), cid, db.AIReplySettings{
AIEnabled: req.AIEnabled, MaxDiscountPercent: req.MaxDiscountPercent,
err := s.settingsApplication().UpsertAIReply(r.Context(), sess.UserID, cid, settingsapp.AIReplySettings{
CookieID: cid, AIEnabled: req.AIEnabled, MaxDiscountPercent: req.MaxDiscountPercent,
MaxDiscountAmount: req.MaxDiscountAmount, MaxBargainRounds: req.MaxBargainRounds,
CustomPrompts: req.CustomPrompts,
})
if err != nil {
if writeSettingsAccountError(w, err) {
return
}
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// writeSettingsAccountError 将应用层账号归属错误映射为旧接口兼容的 HTTP 状态。
func writeSettingsAccountError(w http.ResponseWriter, err error) bool {
if errors.Is(err, settingsapp.ErrAccountNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return true
}
if errors.Is(err, settingsapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return true
}
return false
}
// listAIModels 负责listAI模型列表相关处理。
func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
// req 保存 HTTP 层接收的模型目录查询参数。
var req struct {
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
@@ -444,46 +413,14 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存当前管理员会话,用于 AI 密钥使用审计。
// sess 保存当前管理员会话,用于应用服务执行 AI 密钥审计和读取。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// baseURL 保存baseURL,供当前处理流程使用
baseURL := strings.TrimSpace(req.BaseURL)
if baseURL == "" {
// v、err 保存v、err,供当前处理流程使用
v, err := s.Store.Settings.Get(r.Context(), "ai_api_url")
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取AI地址失败")
return
}
baseURL = v
}
if baseURL == "" {
baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
// apiKey 保存apiKey,供当前处理流程使用
apiKey := strings.TrimSpace(req.APIKey)
if apiKey == "" {
// v、err 保存经访问审计后读取的 AI 密钥及错误。
v, err := s.Store.ReadSensitiveSetting(r.Context(), sess.UserID, "ai_api_key", "settings.use", "ai_models")
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取AI Key失败")
return
}
apiKey = v
} else if
// auditErr 表示审计外部传入 AI 密钥时返回的错误。
auditErr := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.use", "ai_models", []string{"ai_api_key"}); auditErr != nil {
// 外部传入的 AI 密钥也属于敏感使用,审计不可用时拒绝继续请求。
writeErr(w, http.StatusInternalServerError, "审计失败")
return
}
// models、err 保存models、err,供当前处理流程使用
models, err := fetchOpenAIModels(r.Context(), baseURL, apiKey)
// models、err 保存应用服务读取的模型名称及错误。
models, err := s.settingsApplication().ListAIModels(r.Context(), sess.UserID, req.BaseURL, req.APIKey)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
return
@@ -491,127 +428,6 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, aiModelsResponse{Models: models})
}
// newSettingsOutboundHTTPClient 保存new设置OutboundHTTPClient,供当前处理流程使用
var newSettingsOutboundHTTPClient = func(baseURL string) (*http.Client, error) {
return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second)
}
// fetchOpenAIModels 负责fetchOpenAI模型列表相关处理。
func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if baseURL == "" {
return nil, fmt.Errorf("AI API 地址为空")
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/models", nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
if strings.TrimSpace(apiKey) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(apiKey))
}
// client、err 保存client、err,供当前处理流程使用
client, err := newSettingsOutboundHTTPClient(baseURL)
if err != nil {
return nil, fmt.Errorf("AI API 地址无效: %w", err)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("读取模型失败: %w", err)
}
defer resp.Body.Close()
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readOpenAIModelsBody(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("读取模型失败: HTTP %d %s", resp.StatusCode, truncate(string(raw), 180))
}
// models、err 保存models、err,供当前处理流程使用
models, err := parseOpenAIModels(raw)
if err != nil {
return nil, err
}
if len(models) == 0 {
return nil, fmt.Errorf("模型列表为空")
}
return models, nil
}
// readOpenAIModelsBody 负责readOpenAI模型列表请求体相关处理。
func readOpenAIModelsBody(r io.Reader) ([]byte, error) {
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(r, maxOpenAIModelsResponseBytes+1))
if err != nil {
return nil, err
}
if len(raw) > maxOpenAIModelsResponseBytes {
return nil, fmt.Errorf("模型列表响应超过 %d MiB", maxOpenAIModelsResponseBytes>>20)
}
return raw, nil
}
// parseOpenAIModels 负责parseOpenAI模型列表相关处理。
func parseOpenAIModels(raw []byte) ([]string, error) {
// payload 保存请求载荷,供当前处理流程使用
var payload any
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("解析模型列表失败: %w", err)
}
// seen 保存seen,供当前处理流程使用
seen := make(map[string]bool)
// out 保存out,供当前处理流程使用
var out []string
// add 保存add,供当前处理流程使用
add := func(v string) {
v = strings.TrimSpace(v)
if v == "" || seen[v] {
return
}
seen[v] = true
out = append(out, v)
}
// walk 保存walk,供当前处理流程使用
var walk func(any)
walk = func(v any) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case []any:
// item 表示当前遍历过程中的商品
for _, item := range x {
walk(item)
}
case map[string]any:
if // id 保存标识,供当前处理流程使用
id, _ := x["id"].(string); id != "" {
add(id)
} else if // name 保存名称,供当前处理流程使用
name, _ := x["name"].(string); name != "" {
add(name)
}
case string:
add(x)
}
}
if // root、ok 保存root、ok,供当前处理流程使用
root, ok := payload.(map[string]any); ok {
if // data、ok 保存data、ok,供当前处理流程使用
data, ok := root["data"]; ok {
walk(data)
} else if // models、ok 保存models、ok,供当前处理流程使用
models, ok := root["models"]; ok {
walk(models)
}
} else {
walk(payload)
}
return out, nil
}
// ---- 用户设置 ----
// mountUserReal 负责mount用户Real相关处理。
@@ -623,10 +439,10 @@ func (s *Server) mountUserReal(r chi.Router) {
// listUserSettings 负责list用户设置相关处理。
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
// settings、err 保存settings、err,供当前处理流程使用
settings, err := s.Store.UserSettings.AllForUser(r.Context(), sess.UserID)
// settings、err 保存用户设置及查询错误。
settings, err := s.settingsApplication().ListUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -636,12 +452,12 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
// getUserSetting 负责get用户设置相关处理。
func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
// key 保存key,供当前处理流程使用
key := chi.URLParam(r, "key")
// v、err 保存v、err,供当前处理流程使用
v, err := s.Store.UserSettings.GetForUser(r.Context(), sess.UserID, key)
// v、err 保存用户设置值及查询错误。
v, err := s.settingsApplication().GetUser(r.Context(), sess.UserID, key)
if err != nil {
writeJSON(w, http.StatusOK, userSettingResponse{Value: ""})
return
@@ -665,7 +481,7 @@ func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
return
}
// err 是用户设置写入错误。
err := s.Store.UserSettings.SetForUser(r.Context(), sess.UserID, key, req.Value)
err := s.settingsApplication().SetUser(r.Context(), sess.UserID, key, req.Value)
if err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
@@ -0,0 +1,26 @@
package server
import (
"context"
"io"
"xianyu-go/internal/adapter"
)
// maxOpenAIModelsResponseBytes 保留旧测试名称,实际限制由适配器统一维护。
const maxOpenAIModelsResponseBytes = adapter.MaxAIModelsResponseBytes
// fetchOpenAIModels 保留旧测试辅助入口,生产请求已经由设置应用服务编排。
func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) {
return adapter.NewAIModelClient().Fetch(ctx, baseURL, apiKey)
}
// readOpenAIModelsBody 保留旧测试辅助入口,实际读取逻辑由适配器维护。
func readOpenAIModelsBody(reader io.Reader) ([]byte, error) {
return adapter.ReadAIModelsBody(reader)
}
// parseOpenAIModels 保留旧测试辅助入口,实际解析逻辑由适配器维护。
func parseOpenAIModels(raw []byte) ([]string, error) {
return adapter.ParseAIModels(raw)
}
+124 -89
View File
@@ -1,11 +1,10 @@
package server
import (
cardsapp "xianyu-go/internal/application/cards"
chatapp "xianyu-go/internal/application/chat"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// operationResponse 是密码、会话和设置变更接口共用的操作结果 DTO。
@@ -18,6 +17,14 @@ type operationResponse struct {
RequiresRelogin bool `json:"requires_relogin,omitempty"`
}
// longLoginResponse 是长登录设置接口的具名响应 DTO,不包含平台 Cookie。
type longLoginResponse struct {
// CanOpenLongLogin 表示平台是否允许开启长登录。
CanOpenLongLogin bool `json:"can_open_long_login"`
// Enabled 表示平台当前是否已开启长登录。
Enabled bool `json:"enabled"`
}
// messageResponse 是只返回提示文本的简单成功响应 DTO。
type messageResponse struct {
// Message 是接口操作结果说明。
@@ -78,23 +85,23 @@ type chatSessionDTO struct {
UnreadCount int `json:"unread_count"`
}
// newChatSessionDTO 将数据库聊天会话转换为 API DTO。
func newChatSessionDTO(session db.ChatSession) chatSessionDTO {
// newChatSessionDTOFromApplication 将应用层聊天会话转换为 HTTP DTO。
func newChatSessionDTOFromApplication(session chatapp.Session) chatSessionDTO {
return chatSessionDTO{
AccountID: session.CookieID, ChatID: session.ChatID, BuyerID: session.BuyerID,
AccountID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID,
BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID,
ItemTitle: session.ItemTitle, LastMessage: session.LastMessage,
LastMessageAt: session.LastMessageAt, UnreadCount: session.UnreadCount,
}
}
// newChatSessionDTOs 批量转换聊天会话,保持接口响应不直接暴露数据库模型。
func newChatSessionDTOs(sessions []db.ChatSession) []chatSessionDTO {
// newChatSessionDTOsFromApplication 批量转换应用层聊天会话,保持响应不暴露数据库模型。
func newChatSessionDTOsFromApplication(sessions []chatapp.Session) []chatSessionDTO {
// result 是转换后的聊天会话 DTO 列表。
result := make([]chatSessionDTO, 0, len(sessions))
// session 是当前待转换的数据库聊天会话。
// session 表示当前待转换的应用层会话。
for _, session := range sessions {
result = append(result, newChatSessionDTO(session))
result = append(result, newChatSessionDTOFromApplication(session))
}
return result
}
@@ -125,25 +132,6 @@ type chatMessageDTO struct {
SentAt int64 `json:"sent_at"`
}
// newChatMessageDTO 将数据库聊天消息转换为 API DTO。
func newChatMessageDTO(message db.ChatMessage) chatMessageDTO {
return chatMessageDTO{
ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID,
MessageKey: message.MessageKey, Direction: message.Direction,
SenderID: message.SenderID, SenderName: message.SenderName,
MessageType: message.MessageType, Content: message.Content,
Status: message.Status, SentAt: message.SentAt,
}
}
// newChatMessageDTOFromPointer 转换可为空的聊天消息指针,避免成功响应因空值 panic。
func newChatMessageDTOFromPointer(message *db.ChatMessage) chatMessageDTO {
if message == nil {
return chatMessageDTO{}
}
return newChatMessageDTO(*message)
}
// newChatMessageDTOFromApplication 将聊天应用层发送结果转换为 HTTP DTO,避免响应引用数据库模型。
func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO {
if message == nil {
@@ -158,17 +146,6 @@ func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO {
}
}
// newChatMessageDTOs 批量转换聊天消息,保持接口响应与数据库模型解耦。
func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO {
// result 是转换后的聊天消息 DTO 列表。
result := make([]chatMessageDTO, 0, len(messages))
// message 是当前待转换的数据库聊天消息。
for _, message := range messages {
result = append(result, newChatMessageDTO(message))
}
return result
}
// newChatMessageDTOsFromApplication 将聊天应用层消息转换为 HTTP DTO,避免响应暴露数据库模型。
func newChatMessageDTOsFromApplication(messages []chatapp.Message) []chatMessageDTO {
// result 是转换后的聊天消息 DTO 列表。
@@ -537,12 +514,52 @@ type automationRulePageResponse struct {
TriggerCounts map[string]int `json:"trigger_counts"`
}
// automationRunIssueDTO 是自动化异常运行接口对外暴露的具名 DTO。
type automationRunIssueDTO struct {
// ID 是自动化运行的稳定标识。
ID int64 `json:"id"`
// CookieID 是关联账号标识。
CookieID string `json:"cookie_id"`
// OrderID 是关联订单标识。
OrderID string `json:"order_id"`
// TriggerType 是触发运行的事件类型。
TriggerType string `json:"trigger_type"`
// ErrorMessage 是运行进入人工处理状态时记录的原因。
ErrorMessage string `json:"error_message"`
// IssueKind 是应用层归类的异常类型。
IssueKind string `json:"issue_kind"`
// AllowedResolutions 是当前异常允许的人工处理动作。
AllowedResolutions []string `json:"allowed_resolutions"`
// ActionCursor 是下一步动作在计划中的位置。
ActionCursor int `json:"action_cursor"`
// SentCount 是已经确认成功的外部动作数量。
SentCount int `json:"sent_count"`
// UpdatedAt 是运行状态最近更新的时间文本。
UpdatedAt string `json:"updated_at"`
}
// deferredAutomationIssueDTO 是延期任务接口对外暴露的具名 DTO。
type deferredAutomationIssueDTO struct {
// ID 是延期任务的稳定标识。
ID int64 `json:"id"`
// CookieID 是关联账号标识。
CookieID string `json:"cookie_id"`
// TriggerType 是触发延期任务的事件类型。
TriggerType string `json:"trigger_type"`
// ErrorMessage 是任务进入死信状态时记录的原因。
ErrorMessage string `json:"error_message"`
// AttemptCount 是任务已经尝试执行的次数。
AttemptCount int `json:"attempt_count"`
// UpdatedAt 是任务状态最近更新的时间文本。
UpdatedAt string `json:"updated_at"`
}
// automationIssuesResponse 是自动化异常任务接口的具名响应 DTO。
type automationIssuesResponse struct {
// Runs 是需要处理的自动化运行记录。
Runs []db.AutomationRunIssue `json:"runs"`
Runs []automationRunIssueDTO `json:"runs"`
// PendingTasks 是需要处理的延迟任务记录。
PendingTasks []db.DeferredAutomationIssue `json:"pending_tasks"`
PendingTasks []deferredAutomationIssueDTO `json:"pending_tasks"`
}
// orderDetailResponse 是订单详情接口的具名响应 DTO,同时保留旧版顶层字段兼容性。
@@ -701,8 +718,8 @@ type cardResponse struct {
UserID int64 `json:"user_id,omitempty"`
}
// newCardResponse 将数据库卡券模型转换为 HTTP DTO。
func newCardResponse(card db.CardFull) cardResponse {
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
func newCardResponse(card cardsapp.Card) cardResponse {
return cardResponse{
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
@@ -711,11 +728,11 @@ func newCardResponse(card db.CardFull) cardResponse {
}
}
// newCardResponses 批量转换卡券列表,避免直接暴露数据库模型。
func newCardResponses(cards []db.CardFull) []cardResponse {
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
func newCardResponses(cards []cardsapp.Card) []cardResponse {
// result 是转换后的卡券 DTO 列表。
result := make([]cardResponse, 0, len(cards))
// card 是当前待转换的卡券数据库模型。
// card 是当前待转换的卡券应用模型。
for _, card := range cards {
result = append(result, newCardResponse(card))
}
@@ -854,7 +871,63 @@ type categoryRecommendationResponse struct {
// Success 表示类目推荐是否成功。
Success bool `json:"success"`
// Category 是推荐的商品类目。
Category mtop.PublishCategory `json:"category"`
Category publishCategoryResponse `json:"category"`
}
// publishCategoryResponse 是商品类目 HTTP 响应的稳定 DTO,不泄露平台包类型。
type publishCategoryResponse struct {
// CatID 是平台类目标识。
CatID string `json:"cat_id"`
// CatName 是平台类目名称。
CatName string `json:"cat_name"`
// ChannelCatID 是闲鱼频道类目标识。
ChannelCatID string `json:"channel_cat_id,omitempty"`
// TBCatID 是淘宝类目标识。
TBCatID string `json:"tb_cat_id,omitempty"`
}
// publishAutomationConfig 是批量发布预检与详情响应中的自动化配置 DTO。
type publishAutomationConfig struct {
// PaidDelivery 保存付款后自动发货配置。
PaidDelivery publishCardAutomation `json:"paid_delivery"`
// ReviewGift 保存评价后赠品配置。
ReviewGift publishCardAutomation `json:"review_gift"`
// ReviewRequest 保存超时求评价配置。
ReviewRequest publishReviewRequestCfg `json:"review_request"`
}
// publishCardAutomation 是批量发布中的卡密自动化 DTO。
type publishCardAutomation struct {
// Enabled 表示该自动化规则是否启用。
Enabled bool `json:"enabled"`
// Actions 保存按顺序执行的卡密动作。
Actions []publishCardAction `json:"actions"`
// ParseError 保存导入动作文本的解析错误。
ParseError string `json:"-"`
}
// publishCardAction 是单条批量卡密动作 DTO。
type publishCardAction struct {
// CardID 是卡密组标识。
CardID int64 `json:"card_id"`
// DeliveryCount 是每件商品发送的卡密数量。
DeliveryCount int `json:"delivery_count"`
// DelaySeconds 是发送动作的延迟秒数。
DelaySeconds int `json:"delay_seconds"`
}
// publishReviewRequestCfg 是批量发布求评价配置 DTO。
type publishReviewRequestCfg struct {
// Enabled 表示是否启用求评价。
Enabled bool `json:"enabled"`
// AfterShippedHours 是发货后的等待小时数。
AfterShippedHours int `json:"after_shipped_hours"`
// Message 是发送给买家的求评价文案。
Message string `json:"message"`
// MaxAttempts 是最多提醒次数。
MaxAttempts int `json:"max_attempts"`
// DelaySeconds 是提醒动作的延迟秒数。
DelaySeconds int `json:"delay_seconds"`
}
// itemPublishBatchPreviewResponse 是商品批量发布预检接口的具名响应 DTO。
@@ -906,7 +979,7 @@ type itemPublishBatchRowResponse struct {
// Images 是商品图片引用列表。
Images []string `json:"images"`
// Category 是商品发布类目。
Category mtop.PublishCategory `json:"category"`
Category publishCategoryResponse `json:"category"`
// Automation 是发布后自动化配置。
Automation publishAutomationConfig `json:"automation"`
// Status 是当前明细行状态。
@@ -1015,8 +1088,8 @@ type defaultReplyResponse struct {
ReplyOnce bool `json:"reply_once"`
}
// newDefaultReplyResponse 将数据库默认回复转换为 HTTP DTO。
func newDefaultReplyResponse(cookieID string, reply db.DefaultReply) defaultReplyResponse {
// newDefaultReplyResponse 将默认回复应用模型转换为 HTTP DTO。
func newDefaultReplyResponse(cookieID string, reply defaultreplyapp.Reply) defaultReplyResponse {
return defaultReplyResponse{
CookieID: cookieID, Enabled: reply.Enabled, ReplyContent: reply.ReplyContent,
ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce,
@@ -1043,15 +1116,6 @@ type accountTaskSettingsResponse struct {
LastPolishAt int64 `json:"last_polish_at"`
}
// newAccountTaskSettingsResponse 将账号任务数据库设置转换为 HTTP DTO。
func newAccountTaskSettingsResponse(settings db.AccountTaskSettings) accountTaskSettingsResponse {
return accountTaskSettingsResponse{
AccountID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent,
AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime,
LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt,
}
}
// accountTaskRunResponse 是账号任务执行记录的具名 DTO。
type accountTaskRunResponse struct {
// ID 是任务执行记录主键。
@@ -1082,27 +1146,6 @@ type accountTaskRunResponse struct {
FinishedAt int64 `json:"finished_at"`
}
// newAccountTaskRunResponse 将账号任务执行记录转换为 HTTP DTO。
func newAccountTaskRunResponse(run db.AccountTaskRun) accountTaskRunResponse {
return accountTaskRunResponse{
ID: run.ID, RunKey: run.RunKey, AccountID: run.CookieID, TaskType: run.TaskType,
TargetID: run.TargetID, RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount,
FailedCount: run.FailedCount, ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt,
StartedAt: run.StartedAt, FinishedAt: run.FinishedAt,
}
}
// newAccountTaskRunResponses 批量转换账号任务执行记录。
func newAccountTaskRunResponses(runs []db.AccountTaskRun) []accountTaskRunResponse {
// result 是账号任务执行记录 DTO 列表。
result := make([]accountTaskRunResponse, 0, len(runs))
// run 是当前待转换的账号任务执行记录。
for _, run := range runs {
result = append(result, newAccountTaskRunResponse(run))
}
return result
}
// accountTaskSummaryResponse 是手动执行账号任务的统计 DTO。
type accountTaskSummaryResponse struct {
// TaskType 是任务类型。
@@ -1133,14 +1176,6 @@ type accountTaskRunsResponse struct {
Runs []accountTaskRunResponse `json:"runs"`
}
// newAccountTaskSummaryResponse 将自动化中心统计转换为 HTTP DTO。
func newAccountTaskSummaryResponse(summary automation.AccountTaskSummary) accountTaskSummaryResponse {
return accountTaskSummaryResponse{
TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success,
Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message,
}
}
// adminUserResponse 是管理员用户列表项的具名响应 DTO。
type adminUserResponse struct {
// ID 是用户主键。
+29
View File
@@ -154,3 +154,32 @@ func TestStartBackgroundTaskContextWaitsForTaskExit(t *testing.T) {
t.Fatal("后台任务退出后等待未完成")
}
}
// TestWaitForBackgroundContextBoundsTimeout 验证后台任务等待超时不会阻塞后续生命周期收束。
func TestWaitForBackgroundContextBoundsTimeout(t *testing.T) {
// srv 是使用零值字段验证后台完成信号惰性初始化的 Server。
srv := &Server{}
// taskStarted、releaseTask 分别表示任务已经登记和允许任务退出的信号。
taskStarted := make(chan struct{})
// releaseTask 是允许阻塞测试任务退出的信号。
releaseTask := make(chan struct{})
srv.startBackgroundTaskContext("超时等待任务", context.Background(), func() {
close(taskStarted)
<-releaseTask
})
<-taskStarted
// timeoutContext 是限制第一次等待时长的上下文。
timeoutContext, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if srv.waitForBackgroundContext(timeoutContext) {
t.Fatal("后台任务未退出时不应提前报告完成")
}
// releaseTask 允许后台任务退出,验证后续等待可以直接观察完成信号。
close(releaseTask)
// completedContext 是用于确认任务退出的有限等待上下文。
completedContext, completedCancel := context.WithTimeout(context.Background(), time.Second)
defer completedCancel()
if !srv.waitForBackgroundContext(completedContext) {
t.Fatalf("后台任务退出后等待失败: %v", completedContext.Err())
}
}
-63
View File
@@ -1,63 +0,0 @@
package server
import (
"context"
"database/sql"
"errors"
"xianyu-go/internal/db"
)
// transactionRepository 定义 Server 统一事务入口所需的最小持久化能力。
type transactionRepository interface {
// WithTransaction 在一个事务中执行工作并负责提交或回滚。
WithTransaction(ctx context.Context, work func(*sql.Tx) error) error
}
// storeTransactionRepository 将完整 Store 适配为事务执行窄 repository。
type storeTransactionRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// WithTransaction 创建、提交或回滚数据库事务。
func (r storeTransactionRepository) WithTransaction(ctx context.Context, work func(*sql.Tx) error) error {
if r.store == nil || r.store.DB == nil {
return errors.New("事务 repository 未初始化")
}
// tx 是本次用例使用的数据库事务。
// err 表示事务创建错误。
// tx、err 保存tx、err,供当前处理流程使用
tx, err := r.store.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
// committed 标识事务是否已经成功提交,避免提交失败后重复处理回滚错误。
committed := false
defer func() {
if !committed {
_ = tx.Rollback()
}
}()
if // err 保存err,供当前处理流程使用
err := work(tx); err != nil {
return err
}
// err 表示事务提交错误。
if err := tx.Commit(); err != nil {
return err
}
committed = true
return nil
}
// newStoreTransactionRepository 从完整 Store 构造事务执行窄 repository。
func newStoreTransactionRepository(store *db.Store) transactionRepository {
if store == nil || store.DB == nil {
return nil
}
return storeTransactionRepository{store: store}
}
// 确保 Store 适配器始终覆盖事务执行边界。
var _ transactionRepository = storeTransactionRepository{}
+3 -3
View File
@@ -10,12 +10,12 @@ import (
// TestWithTransactionCommitAndRollback 验证统一事务入口能够提交成功操作并回滚失败操作。
func TestWithTransactionCommitAndRollback(t *testing.T) {
// srv 是使用测试数据库的 Server。
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 是本测试使用的可取消上下文。
ctx := context.Background()
// createErr 是创建测试表失败时的错误。
if _, createErr := srv.Store.DB.ExecContext(ctx, `CREATE TABLE unit_of_work_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil {
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 是提交事务执行结果。
@@ -43,7 +43,7 @@ func TestWithTransactionCommitAndRollback(t *testing.T) {
// count 是事务提交后测试表中的记录数。
var count int
if // err 保存err,供当前处理流程使用
err := srv.Store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil {
err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil {
t.Fatalf("查询事务测试结果失败: %v", err)
}
if count != 1 {