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

将账号、认证、管理员、分析、自动化、卡券、聊天、商品、关键词、设置和订单能力迁移到 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

+9 -1
View File
@@ -329,7 +329,15 @@ func runServer(parent context.Context, opts serverOptions) error {
go renewalScheduler.Run(ctx)
// srv 是完成依赖校验并注入聊天服务后的 HTTP 应用实例。
srv, err := server.New(store, mgr, opts.secure, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService))
// serverDependencies 封装 HTTP 服务需要的持久化适配器,避免 Server 直接持有 Store。
serverDependencies, dependencyErr := adapter.NewDependencies(store)
if dependencyErr != nil {
return fmt.Errorf("构造 HTTP 基础设施依赖失败: %w", dependencyErr)
}
// authentication 保存 HTTP 会话中间件所需的认证实现;会话 Cookie 的 Secure 策略由启动参数决定。
authentication := &auth.Service{Store: store, Logger: logger, Secure: opts.secure}
// srv、err 保存 HTTP 服务构造结果及失败原因。
srv, err := server.New(serverDependencies, authentication, mgr, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService))
if err != nil {
return fmt.Errorf("构造 HTTP 服务失败: %w", err)
}
+27
View File
@@ -0,0 +1,27 @@
# 生命周期与后台任务清单
本文是重构计划阶段 5 的持续审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界,
用于逐项关闭“生命周期与删除 fencing”父切片;清单本身不代表对应组件已经满足完成条件。
## 组件清单
| 组件/入口 | 所有者 | Context 来源 | 停止/关闭 | 等待/观测 | 当前证据 | 剩余风险 |
| --- | --- | --- | --- | --- | --- | --- |
| `server.Server` HTTP 与后台任务 | `cmd/server` | `Server.Start` 接收的进程 Context;后台任务继承生命周期 Context | `Server.Stop(ctx)`,关闭 HTTP、恢复任务和后台计数 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 仍需把所有新后台入口统一登记并审计启动顺序 |
| 订单刷新 worker/recovery | `server.Server` | Server 生命周期 Context;恢复扫描使用调用方 Context | worker 终止、租约 fencing、终态写入使用受控 Context | 任务注册表记录 running/succeeded/failed/canceled/timed_out | 订单刷新生命周期与租约测试 | 取消端点和统一运维查询仍待收口 |
| 商品批量发布 worker/recovery | `server.Server` | Server 生命周期 Context;取消后的本地收口使用独立补偿 Context | worker cancel、租约 token、批次终态补偿写入 | 任务注册表与批次状态 | 批量取消 race、应用 BatchRunner 测试 | 单行平台适配仍在 Server,恢复指标和统一查询待补齐 |
| 订单 reconciliation worker | `server.Server` | Server 生命周期 Context | 扫描器停止时取消当前扫描 | 后台任务注册表和补偿记录状态 | reconciliation 成功/失败重试测试 | 指数退避和更完整运维操作待补齐 |
| `account.Manager` 账号运行时集合 | `cmd/server` | `StartAll`/`Start` 调用方 Context | `StopContext`、`StopAllContext`,全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing 和 race 测试 | 运行时内部任务仍需纳入统一清单 |
| `engine.Account` 单账号运行时 | `account.Manager` | `Account.Run(parent)` | `StopContext` 取消运行 Context 并等待连接/任务退出 | `StopContext` 返回错误;运行状态可查询 | Engine lifecycle 与 credential coordinator 测试 | 消息发送、重连和 recorder 子任务需要逐一核对 Join 边界 |
| 浏览器 `Manager` | `cmd/server`/账号流程 | 每次调用的 Context;关闭使用 `CloseContext` | 关闭 fencing,等待活动调用归零,再关闭 Playwright | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断 |
| 续期 `renewal.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | `StopContext` 幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并调用方仍需统一审计 |
| 自动化 `automation.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | Context 取消后停止调度 | `WaitContext` | scheduler 与结果收口测试 | 自动化准备和外部动作旁路仍需完整盘点 |
| 通知 outbox worker | `cmd/server` | `Start(ctx)` 调用方 Context | Context 取消后停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程仍待补齐 |
| WebSocket/聊天后台发送任务 | `server.Server`/`chat.Service` | 请求或服务生命周期 Context | 请求取消、连接关闭或服务停止;handler 清理阶段先取消并关闭连接 | handler 等待读取 goroutine 退出,发送结果和连接状态仍由连接生命周期观测 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 其他实时连接的统一 owner/Join 证据仍待完善 |
## 使用规则
1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。
2. 每个组件完成生命周期迁移后,必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动完成。
3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。
4. 本表中标记为“剩余风险”的项目未满足父切片关闭条件前,阶段 5 必须保持“进行中”。
File diff suppressed because it is too large. Load diff
+7
View File
@@ -761,6 +761,13 @@ test('getCards 解析 JSON 和损坏 JSON 的卡密接口配置', /* 当前回
expect(cards[1].api_config).toBeUndefined();
});
test('getCards 将后端空响应归一化为空列表', /* 当前回调防止空卡密响应阻断自动化规则账号加载。 */ async () => {
// fetchMock 模拟兼容后端返回 JSON null 的卡密列表响应。
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(null));
vi.stubGlobal('fetch', fetchMock);
await expect(getCards()).resolves.toEqual([]);
});
test('默认回复 API 补齐空字段默认值', /* 当前回调验证默认回复字段归一化和保存载荷。 */ async () => {
// fetchMock 是默认回复读取和保存接口的网络替身。
const fetchMock = vi.fn()
+1 -1
View File
@@ -592,7 +592,7 @@ export const getCards = async (options?: RequestControlOptions): Promise<Card[]>
// res 接口响应结果,用于当前 API 处理流程。
const res = await get<Card[] | CardListResponse>('/api/v1/cards', undefined, options);
// cards 卡密列表,用于当前 API 处理流程。
const cards = Array.isArray(res) ? res : (res.cards || []);
const cards = Array.isArray(res) ? res : (res?.cards || []);
return cards.map(normalizeCard);
};
+84
View File
@@ -0,0 +1,84 @@
package adapter
import (
"context"
"errors"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// AccountLoginAuditRepository 将账号登录审计应用 Port 适配为数据库窄写入。
type AccountLoginAuditRepository struct {
// store 保存数据库聚合入口,仅在基础设施适配器内部使用。
store *db.Store
}
// NewAccountLoginAuditRepository 创建账号登录审计数据库适配器。
func NewAccountLoginAuditRepository(store *db.Store) *AccountLoginAuditRepository {
return &AccountLoginAuditRepository{store: store}
}
// MarkLogin 保存账号最近一次成功登录方式和时间。
func (r *AccountLoginAuditRepository) MarkLogin(ctx context.Context, accountID, method string, at int64) error {
// validateErr 表示适配器或 Cookie 仓储未初始化,阻止审计写入继续访问空依赖。
if validateErr := r.validateCookies(); validateErr != nil {
return validateErr
}
return r.store.Cookies.MarkLogin(ctx, accountID, method, at)
}
// SetStatusWithReason 在登录成功后启用账号并清空禁用原因。
func (r *AccountLoginAuditRepository) SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error {
// validateErr 表示适配器或 Cookie 仓储未初始化,阻止账号状态写入访问空依赖。
if validateErr := r.validateCookies(); validateErr != nil {
return validateErr
}
return r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason)
}
// AddLoginLog 将应用层审计模型转换为数据库模型并写入;审计仓储未装配时保持旧的兼容空操作。
func (r *AccountLoginAuditRepository) AddLoginLog(ctx context.Context, log accountapp.LoginAuditLog) error {
// validateErr 表示数据库适配器未初始化,阻止审计日志转换访问空 Store。
if validateErr := r.validateStore(); validateErr != nil {
return validateErr
}
if r.store.LoginLogs == nil {
return nil
}
return r.store.LoginLogs.Add(ctx, db.AccountLoginLog{
CookieID: log.AccountID,
UserID: log.UserID,
OwnerID: log.UserID,
AccountIdentifier: log.AccountID,
Method: log.Method,
Status: log.Status,
Message: log.Message,
TriggerReason: log.TriggerReason,
FailureReason: log.FailureReason,
ErrorMessage: log.Message,
CreatedAt: log.OccurredAt,
})
}
// validateStore 检查审计适配器是否具备数据库聚合入口。
func (r *AccountLoginAuditRepository) validateStore() error {
if r == nil || r.store == nil {
return errors.New("账号登录审计数据库适配器未初始化")
}
return nil
}
// validateCookies 检查账号状态和登录方式写入所需的 Cookie 仓储。
func (r *AccountLoginAuditRepository) validateCookies() error {
// validateErr 表示数据库聚合入口缺失,需在检查 Cookie 仓储前原样返回。
if validateErr := r.validateStore(); validateErr != nil {
return validateErr
}
if r.store.Cookies == nil {
return errors.New("账号登录审计 Cookie 仓储未初始化")
}
return nil
}
var _ accountapp.LoginAuditRepository = (*AccountLoginAuditRepository)(nil)
@@ -0,0 +1,76 @@
package adapter
import (
"context"
"errors"
"testing"
accountapp "xianyu-go/internal/application/account"
)
// TestAccountLoginAuditRepositoryMapping 验证登录审计应用模型到 SQLite 数据模型的字段映射。
func TestAccountLoginAuditRepositoryMapping(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试存储的登录审计适配器。
repository := NewAccountLoginAuditRepository(store)
// ctx 是本测试数据库操作共用的非取消上下文。
ctx := context.Background()
// markErr 保存登录方式写入结果。
if markErr := repository.MarkLogin(ctx, "cid", accountapp.LoginMethodQRScan, 123); markErr != nil {
t.Fatalf("写入登录方式失败: %v", markErr)
}
// statusErr 保存账号启用状态写入结果。
if statusErr := repository.SetStatusWithReason(ctx, "cid", true, ""); statusErr != nil {
t.Fatalf("写入账号状态失败: %v", statusErr)
}
// logErr 保存登录审计日志写入结果。
if logErr := repository.AddLoginLog(ctx, accountapp.LoginAuditLog{
AccountID: "cid", UserID: 1, Method: accountapp.LoginMethodQRScan,
Status: accountapp.LoginStatusSuccess, Message: "扫码登录成功",
TriggerReason: "扫码登录", OccurredAt: 123,
}); logErr != nil {
t.Fatalf("写入登录审计失败: %v", logErr)
}
// detail 保存数据库返回的非敏感登录方式字段。
detail, detailErr := store.Cookies.GetSummaryOwned(ctx, 1, "cid")
if detailErr != nil || detail.LoginMethod != accountapp.LoginMethodQRScan || detail.LastLoginAt != 123 {
t.Fatalf("登录方式映射异常 detail=%+v err=%v", detail, detailErr)
}
// logs 保存数据库返回的登录审计记录。
logs, logsErr := store.LoginLogs.ListByCookie(ctx, "cid", 1)
if logsErr != nil || len(logs) != 1 || logs[0].OwnerID != 1 || logs[0].AccountIdentifier != "cid" || logs[0].TriggerReason != "扫码登录" || logs[0].ErrorMessage != "扫码登录成功" {
t.Fatalf("登录审计映射异常 logs=%+v err=%v", logs, logsErr)
}
}
// TestAccountLoginAuditRepositoryInfrastructureErrors 验证适配器缺少依赖或数据库关闭时不伪装成功。
func TestAccountLoginAuditRepositoryInfrastructureErrors(t *testing.T) {
// missingErr 保存缺少 Store 时的装配错误。
missingErr := NewAccountLoginAuditRepository(nil).MarkLogin(context.Background(), "cid", "manual", 1)
if missingErr == nil {
t.Fatal("缺少 Store 时应返回装配错误")
}
// store 是随后主动关闭数据库连接的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定已关闭数据库的登录审计适配器。
repository := NewAccountLoginAuditRepository(store)
// closeErr 保存主动关闭测试数据库的资源释放结果。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// markErr 保存数据库关闭后登录方式写入结果。
markErr := repository.MarkLogin(context.Background(), "cid", "manual", 1)
if markErr == nil {
t.Fatal("数据库关闭后应返回登录方式写入错误")
}
// logErr 保存数据库关闭后审计日志写入结果。
logErr := repository.AddLoginLog(context.Background(), accountapp.LoginAuditLog{AccountID: "cid", Method: "manual"})
if logErr == nil || errors.Is(logErr, accountapp.ErrLoginAuditUnavailable) {
t.Fatalf("数据库故障应透传而非伪装应用装配错误: %v", logErr)
}
}
var _ accountapp.LoginAuditRepository = (*AccountLoginAuditRepository)(nil)
@@ -0,0 +1,316 @@
package adapter
import (
"context"
"errors"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
)
// AccountLoginRepository 将账号登录、扫码凭证和非敏感账号摘要能力适配到应用端口。
// 该类型是唯一接触 Store、加密 metadata 和浏览器 Cookie 快照的实现。
type AccountLoginRepository struct {
// store 保存数据库聚合入口;明文凭证只在本适配器的短调用期间存在。
store *db.Store
}
// NewAccountLoginRepository 构造账号登录数据库适配器;缺少数据库依赖时返回仍可安全失败的实例。
func NewAccountLoginRepository(store *db.Store) *AccountLoginRepository {
return &AccountLoginRepository{store: store}
}
// LockCredentials 串行化同一账号的凭证变更;缺少 Store 时返回无副作用的解锁函数。
func (r *AccountLoginRepository) LockCredentials(accountID string) func() {
if r == nil || r.store == nil {
return func() {}
}
return r.store.LockAccountCredentials(accountID)
}
// CreateCookieOwned 原子校验账号归属并写入 Cookie,明文不会离开数据库适配器。
func (r *AccountLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
// createErr 保存账号 Cookie 创建结果;并发占用会转换为应用层稳定错误。
createErr := r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
if errors.Is(createErr, db.ErrAlreadyExists) {
return accountapp.ErrAlreadyExists
}
if errors.Is(createErr, db.ErrForbidden) {
return accountapp.ErrForbidden
}
if errors.Is(createErr, db.ErrNotFound) {
return accountapp.ErrNotFound
}
return createErr
}
// LoadPlatformDetail 读取平台调用所需的窄凭证视图,并补充非敏感刷新版本。
func (r *AccountLoginRepository) LoadPlatformDetail(ctx context.Context, accountID string) (*accountapp.CredentialDetail, error) {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return nil, validationErr
}
// data 保存只包含 Cookie、metadata 和平台运行设置的窄查询结果;queryErr 保存查询错误。
data, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if queryErr != nil {
if errors.Is(queryErr, db.ErrNotFound) {
// 返回应用层哨兵并保留数据库错误链,兼容仍在迁移中的基础设施调用方。
return nil, errors.Join(accountapp.ErrCredentialNotFound, queryErr)
}
return nil, queryErr
}
// summary 保存不含凭证的账号摘要,用于乐观冲突检查。
summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID)
if summaryErr != nil {
return nil, summaryErr
}
return &accountapp.CredentialDetail{
ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON,
ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt,
}, nil
}
// UpdateFlatCookieOwned 更新扁平 Cookie 并移除旧的完整浏览器快照。
func (r *AccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context, detail *accountapp.CredentialDetail, cookies string) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
if detail == nil {
return db.ErrNotFound
}
// metadata 保存剔除完整快照后的加密元数据,避免旧快照与新扁平 Cookie 不一致。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix())
}
// UpdateRenewalCookie 保存平台返回的 Cookie 和 metadata。
func (r *AccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at)
}
// ClearTokens 清理凭证变化后失效的旧 Token;未装配 Token 仓储时保持兼容空操作。
func (r *AccountLoginRepository) ClearTokens(ctx context.Context, accountID string) error {
// validationErr 表示数据库适配器未完成装配。
validationErr := r.validateStore()
if validationErr != nil {
return validationErr
}
if r.store.Tokens == nil {
return nil
}
return r.store.Tokens.Clear(ctx, accountID)
}
// GetStatus 查询账号是否启用;缺少存储或数据库故障时安全地返回停用。
func (r *AccountLoginRepository) GetStatus(ctx context.Context, accountID string) bool {
if r == nil || r.store == nil || r.store.Cookies == nil {
return false
}
return r.store.Cookies.GetStatus(ctx, accountID)
}
// UpdateProfile 保存账号昵称和头像等非敏感展示资料。
func (r *AccountLoginRepository) UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
return r.store.Cookies.UpdateProfile(ctx, accountID, nickname, avatarURL)
}
// FindAccount 查询扫码账号的存在性和归属,不读取任何凭证字段。
func (r *AccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return accountapp.QRLoginAccount{}, validationErr
}
// ownerID 保存数据库返回的非敏感账号所有者标识;queryErr 保存查询错误。
ownerID, queryErr := r.store.Cookies.GetOwnerID(ctx, accountID)
if queryErr != nil {
if errors.Is(queryErr, db.ErrNotFound) {
return accountapp.QRLoginAccount{}, accountapp.ErrNotFound
}
return accountapp.QRLoginAccount{}, queryErr
}
return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil
}
// UpdateFlatCookieOwnedForQR 更新扫码登录已有账号的扁平 Cookie并清除快照。
func (r *AccountLoginRepository) UpdateFlatCookieOwnedForQR(ctx context.Context, accountID, cookies string) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
// detail 保存仅供适配器内部使用的平台凭证视图;queryErr 保存查询错误。
detail, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if queryErr != nil {
return queryErr
}
// metadata 保存剔除旧快照后的加密元数据。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
}
// UpdateCookieSnapshotOwned 更新扫码 Cookie 并合并完整浏览器快照到加密 metadata。
func (r *AccountLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
// detail 保存仅供适配器内部使用的平台凭证视图;queryErr 保存查询错误。
detail, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
if queryErr != nil {
return queryErr
}
// browserSnapshot 保存转换后的浏览器快照,明文不向应用层或 HTTP 层返回。
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 := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot)
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
}
// GetOwnedSummary 查询指定用户拥有的非敏感账号摘要。
func (r *AccountLoginRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.Summary, error) {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return accountapp.Summary{}, validationErr
}
// summary 保存数据库返回的非敏感账号摘要;queryErr 保存摘要查询错误。
summary, queryErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID)
if queryErr != nil {
if errors.Is(queryErr, db.ErrForbidden) {
return accountapp.Summary{}, accountapp.ErrForbidden
}
if errors.Is(queryErr, 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{}, queryErr
}
return accountapp.Summary{
ID: summary.ID, UserID: summary.UserID, Remark: summary.Remark,
Nickname: summary.Nickname, AvatarURL: summary.AvatarURL,
AutoConfirm: summary.AutoConfirm, PauseDuration: summary.PauseDuration,
PausedUntil: summary.PausedUntil, Username: summary.Username,
ShowBrowser: summary.ShowBrowser, LastRefreshAt: summary.LastRefreshAt,
LoginMethod: summary.LoginMethod,
LastLoginAt: summary.LastLoginAt, CreatedAt: summary.CreatedAt,
}, nil
}
// DeleteOwned 在凭证锁内再次确认账号归属后删除账号,避免停止 fencing 期间误删被替换账号。
func (r *AccountLoginRepository) DeleteOwned(ctx context.Context, userID int64, accountID string) error {
// validationErr 表示数据库或 Cookie 仓储未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return validationErr
}
// unlock 保护最终归属复核与删除之间的账号凭证状态。
unlock := r.LockCredentials(accountID)
defer unlock()
// summaryErr 保存锁内最终归属复核失败的原因。
if _, summaryErr := r.GetOwnedSummary(ctx, userID, accountID); summaryErr != nil {
return summaryErr
}
return r.store.Cookies.Delete(ctx, accountID)
}
// validateStore 检查数据库聚合入口是否已完成装配。
func (r *AccountLoginRepository) validateStore() error {
if r == nil || r.store == nil {
return errors.New("账号登录数据库适配器未初始化")
}
return nil
}
// validateCookies 检查账号凭证仓储是否已完成装配。
func (r *AccountLoginRepository) validateCookies() error {
// validationErr 表示数据库适配器未完成装配。
validationErr := r.validateStore()
if validationErr != nil {
return validationErr
}
if r.store.Cookies == nil {
return errors.New("账号登录 Cookie 仓储未初始化")
}
return nil
}
var _ accountapp.CredentialRepository = (*AccountLoginRepository)(nil)
var _ accountapp.ProfileSummaryRepository = (*AccountLoginRepository)(nil)
var _ accountapp.DeleteSummaryRepository = (*AccountLoginRepository)(nil)
// QRLoginRepository 将账号登录适配器限制为扫码持久化端口,避免应用层接触数据库模型。
type QRLoginRepository struct {
// repository 保存共享的账号凭证适配器。
repository *AccountLoginRepository
}
// NewQRLoginRepository 构造扫码登录专用凭证端口。
func NewQRLoginRepository(store *db.Store) accountapp.QRLoginRepository {
return QRLoginRepository{repository: NewAccountLoginRepository(store)}
}
// LockCredentials 串行化扫码登录对同一账号的凭证变更。
func (r QRLoginRepository) LockCredentials(accountID string) func() {
return r.repository.LockCredentials(accountID)
}
// FindAccount 查询扫码账号的存在性和归属,不读取凭证字段。
func (r QRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
return r.repository.FindAccount(ctx, accountID)
}
// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。
func (r QRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error {
return r.repository.CreateCookieOwned(ctx, accountID, cookies, userID)
}
// UpdateFlatCookieOwned 更新已有账号扁平 Cookie并清除完整快照。
func (r QRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error {
return r.repository.UpdateFlatCookieOwnedForQR(ctx, accountID, cookies)
}
// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。
func (r QRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
return r.repository.UpdateCookieSnapshotOwned(ctx, accountID, cookies, snapshot)
}
// ClearTokens 清理扫码登录前遗留的旧连接 Token。
func (r QRLoginRepository) ClearTokens(ctx context.Context, accountID string) error {
return r.repository.ClearTokens(ctx, accountID)
}
var _ accountapp.QRLoginRepository = QRLoginRepository{}
@@ -0,0 +1,152 @@
package adapter
import (
"context"
"errors"
"testing"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/cookierefresh"
)
// TestAccountLoginRepositoryKeepsPlatformViewNarrow 验证平台凭证 Port 只返回 Cookie 运行所需字段。
func TestAccountLoginRepositoryKeepsPlatformViewNarrow(t *testing.T) {
// store 是包含测试账号和加密凭证的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的数据库上下文。
ctx := context.Background()
// metadata 是带浏览器快照的加密元数据样例。
metadata := cookierefresh.MetadataWithSnapshot(`{"device":"test"}`, []cookierefresh.BrowserCookie{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}})
// updateErr 保存写入平台凭证视图的结果。
if updateErr := store.Cookies.UpdateRenewalCookie(ctx, "cid", "sid=flat", metadata, 123); updateErr != nil {
t.Fatalf("写入平台凭证视图失败: %v", updateErr)
}
// repository 是绑定 SQLite 存储的账号登录适配器。
repository := NewAccountLoginRepository(store)
// detail、loadErr 保存应用 Port 返回的窄凭证视图及错误。
detail, loadErr := repository.LoadPlatformDetail(ctx, "cid")
if loadErr != nil {
t.Fatalf("读取平台凭证视图失败: %v", loadErr)
}
if detail == nil || detail.ID != "cid" || detail.UserID != 1 || detail.Value != "sid=flat" || detail.LastRefreshAt != 123 {
t.Fatalf("平台凭证视图映射异常: %+v", detail)
}
if detail.MetadataJSON == "" || detail.ShowBrowser {
t.Fatalf("平台凭证视图未保留必要 metadata 或浏览器设置: %+v", detail)
}
}
// TestAccountLoginRepositoryUpdatesCookieSnapshot 验证扁平更新清除旧快照而扫码快照更新保留完整作用域。
func TestAccountLoginRepositoryUpdatesCookieSnapshot(t *testing.T) {
// store 是用于验证 Cookie metadata 合并的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的数据库上下文。
ctx := context.Background()
// repository 是绑定测试存储的账号登录适配器。
repository := NewAccountLoginRepository(store)
// initialMetadata 是待被扁平更新清除的旧浏览器快照。
initialMetadata := cookierefresh.MetadataWithSnapshot(`{}`, []cookierefresh.BrowserCookie{{Name: "old", Value: "1", Domain: ".goofish.com", Path: "/"}})
// initialErr 保存旧快照写入结果。
if initialErr := store.Cookies.UpdateRenewalCookie(ctx, "cid", "sid=old", initialMetadata, time.Now().Unix()); initialErr != nil {
t.Fatalf("写入旧快照失败: %v", initialErr)
}
// detail、detailErr 保存扁平更新前的窄凭证视图。
detail, detailErr := repository.LoadPlatformDetail(ctx, "cid")
if detailErr != nil {
t.Fatalf("读取旧凭证视图失败: %v", detailErr)
}
// flatErr 保存扁平 Cookie 更新结果。
if flatErr := repository.UpdateFlatCookieOwned(ctx, detail, "sid=flat"); flatErr != nil {
t.Fatalf("扁平 Cookie 更新失败: %v", flatErr)
}
// flatDetail、flatLoadErr 保存扁平更新后的凭证视图。
flatDetail, flatLoadErr := repository.LoadPlatformDetail(ctx, "cid")
if flatLoadErr != nil {
t.Fatalf("读取扁平 Cookie 失败: %v", flatLoadErr)
}
// complete 表示扁平更新后 metadata 是否仍包含完整浏览器快照。
if _, complete := cookierefresh.SnapshotFromMetadataOK(flatDetail.MetadataJSON); complete {
t.Fatal("扁平 Cookie 更新不应保留旧快照")
}
// snapshotErr 保存扫码快照更新结果。
snapshotErr := repository.UpdateCookieSnapshotOwned(ctx, "cid", "sid=snapshot", []accountapp.CookieSnapshot{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}})
if snapshotErr != nil {
t.Fatalf("扫码快照更新失败: %v", snapshotErr)
}
// snapshotDetail、snapshotLoadErr 保存扫码快照更新后的凭证视图。
snapshotDetail, snapshotLoadErr := repository.LoadPlatformDetail(ctx, "cid")
if snapshotLoadErr != nil {
t.Fatalf("读取扫码快照失败: %v", snapshotLoadErr)
}
// snapshot、snapshotOK 保存适配器合并后的 Cookie 快照及完整性。
snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(snapshotDetail.MetadataJSON)
if !snapshotOK || len(snapshot) != 1 || snapshot[0].Value != "snapshot" {
t.Fatalf("扫码 Cookie 快照未正确保存: ok=%v snapshot=%+v", snapshotOK, snapshot)
}
}
// TestAccountLoginRepositoryMapsOwnershipErrors 验证摘要与扫码账号查询不会泄露跨用户凭证内容。
func TestAccountLoginRepositoryMapsOwnershipErrors(t *testing.T) {
// store 是包含一个账号所有者的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的数据库上下文。
ctx := context.Background()
// repository 是绑定测试存储的账号登录适配器。
repository := NewAccountLoginRepository(store)
// forbiddenSummaryErr 保存跨用户摘要查询的应用错误。
_, forbiddenSummaryErr := repository.GetOwnedSummary(ctx, 2, "cid")
if !errors.Is(forbiddenSummaryErr, accountapp.ErrForbidden) {
t.Fatalf("跨用户摘要应返回应用越权错误,got %v", forbiddenSummaryErr)
}
// missingAccountErr 保存不存在扫码账号的应用错误。
_, missingAccountErr := repository.FindAccount(ctx, "missing")
if !errors.Is(missingAccountErr, accountapp.ErrNotFound) {
t.Fatalf("不存在扫码账号应返回应用不存在错误,got %v", missingAccountErr)
}
// missingStoreErr 保存未装配数据库时的快速失败结果。
missingStoreErr := NewAccountLoginRepository(nil).CreateCookieOwned(ctx, "cid", "secret", 1)
if missingStoreErr == nil {
t.Fatal("未装配数据库时不应伪装凭证写入成功")
}
// duplicateErr 验证并发/重复创建被转换为应用层稳定错误,而不是泄露数据库错误类型。
duplicateErr := repository.CreateCookieOwned(ctx, "cid", "sid=duplicate", 1)
if !errors.Is(duplicateErr, accountapp.ErrAlreadyExists) {
t.Fatalf("重复创建应返回账号已存在错误,got %v", duplicateErr)
}
}
// TestAccountLoginRepositoryMapsMissingPlatformCredential 验证平台凭证缺失时返回应用层哨兵。
func TestAccountLoginRepositoryMapsMissingPlatformCredential(t *testing.T) {
// store、cleanup 保存用于查询不存在账号的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试存储的账号登录适配器。
repository := NewAccountLoginRepository(store)
// loadErr 保存不存在平台账号的窄凭证查询错误。
_, loadErr := repository.LoadPlatformDetail(context.Background(), "missing-platform-account")
if !errors.Is(loadErr, accountapp.ErrCredentialNotFound) {
t.Fatalf("缺失平台账号应返回应用错误: %v", loadErr)
}
}
// TestAccountLoginRepositoryPropagatesDatabaseFailure 验证数据库关闭后凭证 Port 原样报告基础设施错误。
func TestAccountLoginRepositoryPropagatesDatabaseFailure(t *testing.T) {
// store 是随后主动关闭的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定待关闭存储的账号登录适配器。
repository := NewAccountLoginRepository(store)
// closeErr 保存主动关闭数据库的结果。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// loadErr 保存数据库关闭后平台视图查询的错误。
_, loadErr := repository.LoadPlatformDetail(context.Background(), "cid")
if loadErr == nil {
t.Fatal("数据库关闭后应返回凭证查询错误")
}
}
+186
View File
@@ -0,0 +1,186 @@
package adapter
import (
"context"
"errors"
"log/slog"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/cookierefresh"
xrenew "xianyu-go/internal/xianyu/renew"
)
// LongLoginClient 定义长登录平台客户端的最小协议,隔离 Server 与 renew 实现。
type LongLoginClient interface {
// QueryLongLoginSettings 查询平台当前长登录状态,并返回响应 Cookie。
QueryLongLoginSettings(context.Context, string, ...[]cookierefresh.BrowserCookie) (*xrenew.LongLoginSettings, error)
// SetLongLoginSettings 更新平台长登录状态,并返回响应 Cookie。
SetLongLoginSettings(context.Context, string, bool, ...[]cookierefresh.BrowserCookie) (*xrenew.LongLoginSettings, error)
}
// LongLoginAdapter 将长登录平台协议和 Cookie 持久化适配到账号应用端口。
type LongLoginAdapter struct {
// repository 提供凭证锁、平台窄视图和 Cookie 写回能力。
repository accountapp.CredentialRepository
// service 返回当前 Server 配置的平台长登录客户端;函数形式允许测试在构造后替换客户端。
service func() LongLoginClient
// updateRunningCookie 在凭证锁释放后同步已变化的运行时 Cookie。
updateRunningCookie func(context.Context, string, string)
// logger 记录不包含明文 Cookie 的持久化错误。
logger *slog.Logger
}
// NewLongLoginAdapter 构造长登录平台适配器。
func NewLongLoginAdapter(repository accountapp.CredentialRepository, service func() LongLoginClient, updateRunningCookie func(context.Context, string, string), logger *slog.Logger) *LongLoginAdapter {
return &LongLoginAdapter{repository: repository, service: service, updateRunningCookie: updateRunningCookie, logger: logger}
}
// QueryLongLogin 查询长登录状态并持久化平台返回的 Cookie。
func (a *LongLoginAdapter) QueryLongLogin(ctx context.Context, accountID string) (accountapp.LongLoginResult, error) {
return a.execute(ctx, accountID, nil)
}
// SetLongLogin 更新长登录开关并持久化平台返回的 Cookie。
func (a *LongLoginAdapter) SetLongLogin(ctx context.Context, accountID string, enabled bool) (accountapp.LongLoginResult, error) {
return a.execute(ctx, accountID, &enabled)
}
// execute 在凭证锁内读取最新平台视图并完成平台调用,锁只覆盖凭证一致性和写回。
func (a *LongLoginAdapter) execute(ctx context.Context, accountID string, enabled *bool) (accountapp.LongLoginResult, error) {
if a == nil || a.repository == nil || a.service == nil {
return accountapp.LongLoginResult{}, errors.New("长登录适配器未初始化")
}
// unlock 保护本次平台 Cookie 读取和写回;平台网络请求必须在锁外执行。
unlock := a.repository.LockCredentials(accountID)
// detail 保存平台调用所需的 Cookie 与加密 metadata 窄视图。
detail, loadErr := a.repository.LoadPlatformDetail(ctx, accountID)
unlock()
if loadErr != nil {
return accountapp.LongLoginResult{}, loadErr
}
if detail == nil {
return accountapp.LongLoginResult{}, accountapp.ErrNotFound
}
// requestCookies 保存按请求域过滤后的 Cookie;snapshot 保存完整 Cookie Jar(如存在)。
requestCookies, snapshot := longLoginCookies(detail, queryURL(enabled))
// platformResult 保存平台返回的非敏感长登录状态;requestErr 保留平台业务或网络错误。
var platformResult *xrenew.LongLoginSettings
// requestErr 保存平台请求失败;即使失败,响应 Set-Cookie 也可能已完成持久化。
var requestErr error
// client 是本次请求使用的长登录平台客户端。
client := a.service()
if enabled == nil {
if snapshot != nil {
platformResult, requestErr = client.QueryLongLoginSettings(ctx, requestCookies, snapshot)
} else {
platformResult, requestErr = client.QueryLongLoginSettings(ctx, requestCookies)
}
} else if snapshot != nil {
platformResult, requestErr = client.SetLongLoginSettings(ctx, requestCookies, *enabled, snapshot)
} else {
platformResult, requestErr = client.SetLongLoginSettings(ctx, requestCookies, *enabled)
}
// credentialChanged 表示平台响应使本地凭证或完整 Cookie Jar 发生变化。
credentialChanged, persistErr := a.persist(ctx, detail, platformResult, queryURL(enabled))
if persistErr != nil {
return accountapp.LongLoginResult{}, persistErr
}
if credentialChanged && a.updateRunningCookie != nil {
a.updateRunningCookie(ctx, accountID, platformResult.NewCookies)
}
if requestErr != nil {
return toLongLoginResult(platformResult), errors.Join(accountapp.ErrLongLoginPlatform, requestErr)
}
return toLongLoginResult(platformResult), nil
}
// queryURL 返回当前长登录操作对应的官方请求地址。
func queryURL(enabled *bool) string {
if enabled == nil {
return xrenew.QueryLoginSettingsURL
}
return xrenew.SetLoginSettingsURL
}
// longLoginCookies 从平台窄视图提取请求 Cookie 和完整快照,历史扁平账号不伪造快照。
func longLoginCookies(detail *accountapp.CredentialDetail, requestURL string) (string, []cookierefresh.BrowserCookie) {
if detail == nil {
return "", nil
}
// snapshot、complete 保存 metadata 中的完整 Cookie 快照及其权威标记。
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
// header、authoritative 保存按平台请求 URL 过滤后的 Cookie 头及完整性标记。
header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now())
_ = authoritative
return header, snapshot
}
return detail.Value, nil
}
// persist 合并平台响应 Cookie 并在凭证锁内保存最新扁平 Cookie 与完整快照。
func (a *LongLoginAdapter) persist(ctx context.Context, detail *accountapp.CredentialDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) {
if result == nil || detail == nil {
return false, nil
}
// unlock 保护加锁后重读和最终写回,避免平台请求期间持有凭证锁。
unlock := a.repository.LockCredentials(detail.ID)
defer unlock()
// latest 保存平台调用期间可能被其他流程更新后的最新凭证视图。
latest, loadErr := a.repository.LoadPlatformDetail(ctx, detail.ID)
if loadErr != nil || latest == nil {
if a.logger != nil {
a.logger.Warn("读取长登录最新凭证失败", "cookie_id", detail.ID, "err", loadErr)
}
return false, loadErr
}
// metadata 保存合并响应 Cookie 后的加密元数据。
metadata := latest.MetadataJSON
// snapshot、hasSnapshot 保存现有完整 Cookie Jar及其权威标志。
snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(latest.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 {
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 {
result.NewCookies = xrenew.MergeSetCookies(latest.Value, result.SetCookies)
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
}
// changed 表示写回后 Cookie 或 metadata 是否发生变化。
changed := result.NewCookies != latest.Value || metadata != latest.MetadataJSON
if !changed && len(result.SetCookies) == 0 {
return false, nil
}
// persistErr 保存长登录 Cookie 与 metadata 的持久化错误。
if persistErr := a.repository.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); persistErr != nil {
if a.logger != nil {
a.logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", persistErr)
}
return false, persistErr
}
if changed {
// clearErr 保存凭证变化后清理旧连接 Token 的错误;不回滚已成功的 Cookie 写入。
if clearErr := a.repository.ClearTokens(ctx, detail.ID); clearErr != nil && a.logger != nil {
a.logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", clearErr)
}
}
return changed, nil
}
// toLongLoginResult 将平台结果限制为不含 Cookie 的应用层结果。
func toLongLoginResult(result *xrenew.LongLoginSettings) accountapp.LongLoginResult {
if result == nil {
return accountapp.LongLoginResult{}
}
return accountapp.LongLoginResult{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled}
}
+165
View File
@@ -0,0 +1,165 @@
package adapter
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/mtop"
)
// AccountProfilePort 将平台资料查询和账号资料持久化适配到账号应用层。
type AccountProfilePort struct {
// repository 提供凭证快照读取、Cookie 写回和资料保存能力。
repository *AccountLoginRepository
// client 提供平台资料查询能力。
client func() mtop.Client
// updateRunningCookie 在凭证锁释放后同步运行时 Cookie。
updateRunningCookie func(context.Context, string, string)
// recoverSession 在平台返回会话失效时触发账号恢复。
recoverSession func(context.Context, string, error) bool
// logger 记录不包含凭证内容的资料刷新错误。
logger *slog.Logger
}
// NewAccountProfilePort 构造账号资料平台适配器。
func NewAccountProfilePort(repository *AccountLoginRepository, client func() mtop.Client, updateRunningCookie func(context.Context, string, string), recoverSession func(context.Context, string, error) bool, logger *slog.Logger) *AccountProfilePort {
return &AccountProfilePort{repository: repository, client: client, updateRunningCookie: updateRunningCookie, recoverSession: recoverSession, logger: logger}
}
// RefreshProfile 调用平台资料接口、持久化响应 Cookie 和展示资料。
func (p *AccountProfilePort) RefreshProfile(ctx context.Context, input accountapp.ProfileInput) (accountapp.ProfileResult, error) {
if p == nil || p.repository == nil || p.client == nil || p.client() == nil {
return accountapp.ProfileResult{}, errors.New("账号资料适配器未初始化")
}
// fallbackNickname、fallbackAvatar 保存平台失败时的非敏感展示兜底。
fallbackNickname, fallbackAvatar := cachedProfile(input.Summary)
// unlock 保护平台凭证快照读取和响应写回;网络请求发生在解锁后。
unlock := p.repository.LockCredentials(input.AccountID)
// detail、loadErr 保存锁外读取的平台凭证窄视图及其错误。
detail, loadErr := p.repository.LoadPlatformDetail(ctx, input.AccountID)
unlock()
if loadErr != nil || detail == nil || detail.UserID != input.UserID {
if loadErr == nil {
loadErr = accountapp.ErrNotFound
}
return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: truncateProfileError(loadErr)}, nil
}
// requestCtx、session 保存带完整 Jar 或扁平 Cookie 的平台请求上下文。
requestCtx, session := withProfileCookieSession(ctx, detail)
// profile、callErr 保存平台资料结果和调用错误;响应 Cookie 仍会继续处理。
profile, callErr := p.client().FetchUserProfile(requestCtx, detail.Value)
// value、changed、handled、persistErr 保存响应 Cookie 会话写回结果。
value, changed, handled, persistErr := p.persistProfileSession(ctx, detail, session)
if persistErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr))
} else if changed && p.updateRunningCookie != nil {
p.updateRunningCookie(ctx, input.AccountID, value)
}
if !handled && callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != detail.Value {
// flatErr 保存历史扁平 Cookie 写回错误;没有完整 Jar 时才走该兼容分支。
if flatErr := p.repository.UpdateFlatCookieOwned(ctx, detail, profile.UpdatedCookies); flatErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", flatErr))
} else if p.updateRunningCookie != nil {
p.updateRunningCookie(ctx, input.AccountID, profile.UpdatedCookies)
}
}
if callErr != nil {
if p.recoverSession != nil {
p.recoverSession(ctx, input.AccountID, callErr)
}
if p.logger != nil {
p.logger.Warn("刷新账号资料失败", "account", input.AccountID, "err", callErr)
}
return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: truncateProfileError(callErr)}, nil
}
if profile == nil {
return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: "账号资料接口未返回结果"}, nil
}
// nickname 保存归一化后的平台昵称;avatarURL 保存归一化后的非敏感头像地址。
nickname := strings.TrimSpace(profile.Nickname)
// avatarURL 保存归一化后的非敏感平台头像地址。
avatarURL := normalizeProfileAvatar(profile.AvatarURL)
// saveErr 保存资料展示字段写回错误;写回失败不覆盖已获得的平台资料。
if saveErr := p.repository.UpdateProfile(ctx, input.AccountID, nickname, avatarURL); saveErr != nil && p.logger != nil {
p.logger.Warn("保存账号资料失败", "account", input.AccountID, "err", saveErr)
}
if nickname == "" {
nickname = fallbackNickname
}
if avatarURL == "" {
avatarURL = fallbackAvatar
}
return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: nickname, AvatarURL: avatarURL}, nil
}
// withProfileCookieSession 将平台凭证窄视图转换为带快照更新能力的请求会话。
func withProfileCookieSession(ctx context.Context, detail *accountapp.CredentialDetail) (context.Context, *CookieSession) {
// snapshot、ok 保存 metadata 中的完整 Cookie 快照及其有效标记。
if snapshot, ok := SnapshotFromMetadata(detail.MetadataJSON); ok {
return WithCookieSnapshot(ctx, snapshot)
}
return WithFlatCookieSession(ctx, detail.Value)
}
// persistProfileSession 在短凭证锁内保存平台响应 Cookie,避免慢速网络位于锁内。
func (p *AccountProfilePort) persistProfileSession(ctx context.Context, detail *accountapp.CredentialDetail, session *CookieSession) (string, bool, bool, error) {
// unlock 保护响应 Cookie 写回期间的账号凭证一致性。
unlock := p.repository.LockCredentials(detail.ID)
defer unlock()
// latest、loadErr 保存加锁后重读的最新凭证视图及读取错误。
latest, loadErr := p.repository.LoadPlatformDetail(ctx, detail.ID)
if loadErr != nil {
return "", false, true, loadErr
}
return PersistCookieSessionLocked(ctx, p.repository, latest, session)
}
// cachedProfile 生成资料失败时使用的本地非敏感展示值。
func cachedProfile(summary accountapp.Summary) (string, string) {
// nickname 保存资料失败时优先使用的备注或缓存昵称。
nickname := strings.TrimSpace(summary.Remark)
if nickname == "" {
nickname = strings.TrimSpace(summary.Nickname)
}
if nickname == "" {
nickname = "账号 " + shortProfileID(summary.ID)
}
return nickname, normalizeProfileAvatar(summary.AvatarURL)
}
// normalizeProfileAvatar 统一平台返回的头像协议,避免把 HTTP 头像写回展示资料。
func normalizeProfileAvatar(raw string) string {
raw = strings.TrimSpace(raw)
if strings.HasPrefix(raw, "//") {
return "https:" + raw
}
if strings.HasPrefix(raw, "http://") {
return "https://" + strings.TrimPrefix(raw, "http://")
}
return raw
}
// truncateProfileError 限制资料刷新错误长度,避免平台响应原文过长进入 HTTP。
func truncateProfileError(err error) string {
if err == nil {
return ""
}
// message 保存待截断的错误文本,避免平台原文无限进入响应。
message := err.Error()
if len(message) > 180 {
return message[:180]
}
return message
}
// shortProfileID 限制兜底展示中的账号标识长度,避免错误响应或日志暴露完整标识。
func shortProfileID(accountID string) string {
if len(accountID) > 6 {
return accountID[:6]
}
return accountID
}
+179
View File
@@ -0,0 +1,179 @@
package adapter
import (
"context"
"errors"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// ClearTokens 清理 Cookie 更新后失效的旧连接凭证;缺少 Token 仓储时保持兼容空操作。
func (r *AccountSettingsRepository) ClearTokens(ctx context.Context, accountID string) error {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return validationErr
}
if r.store.Tokens == nil {
return nil
}
return r.store.Tokens.Clear(ctx, accountID)
}
// AccountSettingsRepository 将账号设置、登录秘密和暂停状态适配到应用层 Port。
// 明文 Cookie 与登录密码只在本适配器调用数据库加密写入时短暂存在。
type AccountSettingsRepository struct {
// store 保存数据库聚合入口,不向应用层暴露裸数据库连接或模型。
store *db.Store
}
// NewAccountSettingsRepository 构造账号设置数据库适配器。
func NewAccountSettingsRepository(store *db.Store) *AccountSettingsRepository {
return &AccountSettingsRepository{store: store}
}
// LockCredentials 串行化同一账号的敏感设置写入;缺少数据库时返回空操作解锁函数。
func (r *AccountSettingsRepository) LockCredentials(accountID string) func() {
if r == nil || r.store == nil {
return func() {}
}
return r.store.LockAccountCredentials(accountID)
}
// UpdateSettings 将应用层账号设置转换为数据库事务输入并执行归属复核。
func (r *AccountSettingsRepository) UpdateSettings(ctx context.Context, input accountapp.SettingsUpdateInput) (int64, error) {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return 0, validationErr
}
// databaseInput 只在适配器边界携带数据库模型,避免上层依赖 internal/db。
databaseInput := db.AccountSettingsUpdate{
UserID: input.UserID, Value: input.Cookie, Remark: input.Remark,
AutoConfirm: input.AutoConfirm, PauseDuration: input.PauseDuration,
Username: input.Username, Password: input.Password,
ShowBrowser: input.ShowBrowser, ChannelIDs: input.ChannelIDs,
}
// pausedUntil、updateErr 保存数据库返回的暂停截止时间和事务错误。
pausedUntil, updateErr := r.store.Cookies.UpdateSettings(ctx, input.AccountID, databaseInput)
return pausedUntil, normalizeAccountSettingsError(updateErr)
}
// UpdateLoginInfo 将登录用户名、可选密码和浏览器显示设置复用为原子账号设置更新。
func (r *AccountSettingsRepository) UpdateLoginInfo(ctx context.Context, input accountapp.LoginInfoUpdateInput) error {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return validationErr
}
// username 保存兼容旧接口的用户名覆盖值。
username := input.Username
// showBrowser 保存密码登录时是否显示浏览器的配置值。
showBrowser := input.ShowBrowser
// updateErr 保存复用账号设置事务写入登录信息时的错误。
_, updateErr := r.UpdateSettings(ctx, accountapp.SettingsUpdateInput{
UserID: input.UserID, AccountID: input.AccountID,
Username: &username, Password: input.Password, ShowBrowser: &showBrowser,
})
return updateErr
}
// SetStatusOwned 更新账号启用状态,并在数据库访问前验证账号归属。
func (r *AccountSettingsRepository) SetStatusOwned(ctx context.Context, userID int64, accountID string, enabled bool, reason string) error {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return validationErr
}
// ownershipErr 表示状态写入前的账号归属校验错误。
if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil {
return ownershipErr
}
return normalizeAccountSettingsError(r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason))
}
// StatusOwned 查询指定用户账号的启用状态,不读取 Cookie、metadata 或登录密码。
func (r *AccountSettingsRepository) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return false, validationErr
}
// ownershipErr 表示状态读取前的账号归属校验错误。
if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil {
return false, ownershipErr
}
// enabled、statusErr 保存数据库返回的启用状态和查询错误。
enabled, statusErr := r.store.Cookies.Status(ctx, accountID)
return enabled, normalizeAccountSettingsError(statusErr)
}
// SetPauseOwned 更新指定用户账号的暂停时长,并保留零值唤醒待执行任务的数据库语义。
func (r *AccountSettingsRepository) SetPauseOwned(ctx context.Context, userID int64, accountID string, duration int) (int64, error) {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return 0, validationErr
}
// ownershipErr 表示暂停写入前的账号归属校验错误。
if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil {
return 0, ownershipErr
}
// pausedUntil、pauseErr 保存数据库返回的暂停截止时间和写入错误。
pausedUntil, pauseErr := r.store.Cookies.SetPause(ctx, accountID, duration)
return pausedUntil, normalizeAccountSettingsError(pauseErr)
}
// GetPauseOwned 查询指定用户账号的暂停状态和配置时长。
func (r *AccountSettingsRepository) GetPauseOwned(ctx context.Context, userID int64, accountID string) (accountapp.PauseState, error) {
// validationErr 表示账号设置适配器缺少数据库依赖。
if validationErr := r.validate(); validationErr != nil {
return accountapp.PauseState{}, validationErr
}
// ownershipErr 表示暂停读取前的账号归属校验错误。
if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil {
return accountapp.PauseState{}, ownershipErr
}
// paused、pausedUntil、pauseErr 保存数据库返回的暂停标记、截止时间和查询错误。
paused, pausedUntil, pauseErr := r.store.Cookies.IsPaused(ctx, accountID)
if pauseErr != nil {
return accountapp.PauseState{}, normalizeAccountSettingsError(pauseErr)
}
return accountapp.PauseState{Duration: r.store.Cookies.GetPauseDuration(ctx, accountID), PausedUntil: pausedUntil, Paused: paused}, nil
}
// requireOwner 在数据库适配器内部完成非敏感账号归属复核。
func (r *AccountSettingsRepository) requireOwner(ctx context.Context, userID int64, accountID string) error {
// _, ownershipErr 丢弃非敏感摘要本身,只保留账号是否属于当前用户的结论。
if _, ownershipErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID); ownershipErr != nil {
if errors.Is(ownershipErr, db.ErrNotFound) {
// ownerID、ownerErr 用于区分账号不存在与账号属于其他用户,保持越权错误语义。
// ownerID、ownerErr 保存账号所有者标识和归属查询错误。
ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, accountID)
if ownerErr == nil && ownerID != userID {
return accountapp.ErrForbidden
}
}
return normalizeAccountSettingsError(ownershipErr)
}
return nil
}
// validate 检查账号设置适配器所需的数据库依赖是否已装配。
func (r *AccountSettingsRepository) validate() error {
if r == nil || r.store == nil || r.store.Cookies == nil {
return errors.New("账号设置数据库 repository 未初始化")
}
return nil
}
// normalizeAccountSettingsError 将数据库所有权错误转换为应用层稳定错误,不泄露数据库模型。
func normalizeAccountSettingsError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, db.ErrNotFound) {
return accountapp.ErrNotFound
}
if errors.Is(err, db.ErrForbidden) {
return accountapp.ErrForbidden
}
return err
}
var _ accountapp.SettingsRepository = (*AccountSettingsRepository)(nil)
+145
View File
@@ -0,0 +1,145 @@
package adapter
import (
"context"
"errors"
"testing"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// TestAccountSettingsRepositoryRejectsMissingStore 验证账号设置适配器缺少数据库时所有入口均快速失败。
func TestAccountSettingsRepositoryRejectsMissingStore(t *testing.T) {
// repository 保存未装配数据库的账号设置适配器。
repository := NewAccountSettingsRepository(nil)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// err 保存缺少数据库时的账号设置写入错误。
if _, err := repository.UpdateSettings(ctx, accountapp.SettingsUpdateInput{AccountID: "cid"}); err == nil {
t.Fatal("UpdateSettings 缺少数据库时不应成功")
}
// err 保存缺少数据库时的登录信息写入错误。
if err := repository.UpdateLoginInfo(ctx, accountapp.LoginInfoUpdateInput{AccountID: "cid"}); err == nil {
t.Fatal("UpdateLoginInfo 缺少数据库时不应成功")
}
// err 保存缺少数据库时的状态写入错误。
if err := repository.SetStatusOwned(ctx, 1, "cid", true, ""); err == nil {
t.Fatal("SetStatusOwned 缺少数据库时不应成功")
}
// err 保存缺少数据库时的状态读取错误。
if _, err := repository.StatusOwned(ctx, 1, "cid"); err == nil {
t.Fatal("StatusOwned 缺少数据库时不应成功")
}
// err 保存缺少数据库时的暂停写入错误。
if _, err := repository.SetPauseOwned(ctx, 1, "cid", 1); err == nil {
t.Fatal("SetPauseOwned 缺少数据库时不应成功")
}
// err 保存缺少数据库时的暂停读取错误。
if _, err := repository.GetPauseOwned(ctx, 1, "cid"); err == nil {
t.Fatal("GetPauseOwned 缺少数据库时不应成功")
}
// err 保存缺少数据库时的旧 Token 清理错误。
if err := repository.ClearTokens(ctx, "cid"); err == nil {
t.Fatal("ClearTokens 缺少数据库时不应成功")
}
}
// TestAccountSettingsRepositoryWritesAndReadsSettings 验证账号设置、登录秘密、状态和暂停端口的真实 SQLite 行为。
func TestAccountSettingsRepositoryWritesAndReadsSettings(t *testing.T) {
// XIANYU_DATA_KEY 让本测试验证启用密钥时登录秘密确实加密落盘。
t.Setenv("XIANYU_DATA_KEY", "account-settings-test-key")
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的账号设置适配器。
repository := NewAccountSettingsRepository(store)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// admin、userErr 保存测试账号所属用户和查询错误。
admin, userErr := store.Users.GetByUsername(ctx, "admin")
if userErr != nil {
t.Fatalf("GetByUsername: %v", userErr)
}
// remark、password 保存本次设置写入的非敏感备注和敏感密码输入。
remark := "新备注"
password := "new-password" // password 保存仅用于适配器加密写入的测试秘密。
// enabled、showBrowser 保存账号开关设置。
enabled, showBrowser := true, false
// updateErr 保存账号设置事务写入错误。
_, updateErr := repository.UpdateSettings(ctx, accountapp.SettingsUpdateInput{
UserID: admin.ID, AccountID: "cid", Remark: &remark, AutoConfirm: &enabled,
Username: ptrString("login-user"), Password: &password, ShowBrowser: &showBrowser,
})
if updateErr != nil {
t.Fatalf("UpdateSettings: %v", updateErr)
}
// detail、detailErr 保存数据库返回的兼容详情,用于确认敏感字段由数据库加密保存。
detail, detailErr := store.Cookies.GetDetails(ctx, "cid")
if detailErr != nil || detail.Remark != remark || !detail.AutoConfirm || detail.Username != "login-user" || detail.ShowBrowser {
t.Fatalf("settings detail=%+v err=%v", detail, detailErr)
}
// storedPassword 保存数据库中加密后的密码字段,仅用于确认敏感值未以明文落盘。
var storedPassword string
// scanErr 保存读取数据库加密字段的错误。
if scanErr := store.DB.QueryRowContext(ctx, `SELECT password FROM cookies WHERE id=?`, "cid").Scan(&storedPassword); scanErr != nil {
t.Fatalf("读取加密密码字段: %v", scanErr)
}
if storedPassword == password {
t.Fatal("登录密码不应以明文保存")
}
// statusErr 保存状态写入错误。
statusErr := repository.SetStatusOwned(ctx, admin.ID, "cid", false, "manual")
if statusErr != nil {
t.Fatalf("SetStatusOwned: %v", statusErr)
}
// status、statusErr 保存状态读取结果和错误。
status, statusErr := repository.StatusOwned(ctx, admin.ID, "cid")
if statusErr != nil || status {
t.Fatalf("StatusOwned status=%v err=%v", status, statusErr)
}
// pausedUntil、pauseErr 保存暂停写入结果和错误。
pausedUntil, pauseErr := repository.SetPauseOwned(ctx, admin.ID, "cid", 5)
if pauseErr != nil || pausedUntil == 0 {
t.Fatalf("SetPauseOwned until=%d err=%v", pausedUntil, pauseErr)
}
// pauseState、pauseErr 保存暂停查询结果和错误。
pauseState, pauseErr := repository.GetPauseOwned(ctx, admin.ID, "cid")
if pauseErr != nil || pauseState.Duration != 5 || !pauseState.Paused {
t.Fatalf("GetPauseOwned state=%+v err=%v", pauseState, pauseErr)
}
// other、otherErr 保存第二个用户,确保跨用户测试命中真实账号但不属于当前用户。
if _, otherCreateErr := store.Users.Create(ctx, "other", "other@example.com", "pw"); otherCreateErr != nil {
t.Fatalf("Create other user: %v", otherCreateErr)
}
// other、otherErr 保存第二个用户及其查询错误。
other, otherErr := store.Users.GetByUsername(ctx, "other")
if otherErr != nil {
t.Fatalf("GetByUsername other: %v", otherErr)
}
// wrongStatusErr 保存跨用户状态更新错误,确认适配器不会越权写入。
wrongStatusErr := repository.SetStatusOwned(ctx, other.ID, "cid", true, "")
if !errors.Is(wrongStatusErr, accountapp.ErrForbidden) && !errors.Is(wrongStatusErr, db.ErrForbidden) {
t.Fatalf("跨用户状态更新错误=%v", wrongStatusErr)
}
}
// TestAccountSettingsRepositoryClearTokensWithoutTokenStore 验证未装配 Token 仓储时清理动作保持兼容空操作。
func TestAccountSettingsRepositoryClearTokensWithoutTokenStore(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的账号设置适配器。
repository := NewAccountSettingsRepository(store)
// tokenStore 保存原始 Token 仓储并暂时清空,模拟最小装配场景。
tokenStore := store.Tokens
store.Tokens = nil
defer func() { store.Tokens = tokenStore }()
// err 保存无 Token 仓储时的兼容清理结果。
if err := repository.ClearTokens(context.Background(), "cid"); err != nil {
t.Fatalf("未装配 Token 仓储时不应失败: %v", err)
}
}
// ptrString 返回指向给定字符串的输入指针,供设置端口测试构造可选字段。
func ptrString(value string) *string { return &value }
+164
View File
@@ -0,0 +1,164 @@
package adapter
import (
"context"
"errors"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// AccountSummaryRepository 将数据库账号摘要查询适配为应用层 Port,不向上层暴露数据库模型或凭证字段。
type AccountSummaryRepository struct {
// store 保存数据库聚合入口,仅用于调用窄账号摘要查询。
store *db.Store
}
// NewAccountSummaryRepository 构造账号摘要数据库适配器。
func NewAccountSummaryRepository(store *db.Store) *AccountSummaryRepository {
return &AccountSummaryRepository{store: store}
}
// ListOwnedIDs 查询指定用户的账号 ID 列表,不解密任何凭证。
func (r *AccountSummaryRepository) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return nil, validationErr
}
return r.store.Cookies.ListOwnedIDs(ctx, userID)
}
// ListSummaries 查询指定用户的非敏感账号摘要并转换为应用模型。
func (r *AccountSummaryRepository) ListSummaries(ctx context.Context, userID int64) ([]accountapp.AccountSummary, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return nil, validationErr
}
// records、queryErr 保存数据库摘要行及查询错误。
records, queryErr := r.store.Cookies.ListSummaries(ctx, userID)
if queryErr != nil {
return nil, normalizeAccountSummaryError(queryErr)
}
// summaries 保存与数据库模型解耦的应用摘要列表。
summaries := make([]accountapp.AccountSummary, 0, len(records))
// record 表示当前待转换的数据库账号摘要。
for _, record := range records {
summaries = append(summaries, accountSummaryModel(record))
}
return summaries, nil
}
// GetOwnedSummary 查询指定用户的单个非敏感账号摘要。
func (r *AccountSummaryRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.AccountSummary, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return accountapp.AccountSummary{}, validationErr
}
// record、queryErr 保存数据库摘要行及查询错误。
record, queryErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID)
if queryErr != nil {
return accountapp.AccountSummary{}, normalizeAccountSummaryError(queryErr)
}
return accountSummaryModel(record), nil
}
// ExistsOwned 判断账号是否属于指定用户,仅返回非敏感存在性结论。
func (r *AccountSummaryRepository) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return false, validationErr
}
return r.store.Cookies.ExistsOwned(ctx, userID, accountID)
}
// GetOwnerID 查询指定账号所属用户标识,不读取 Cookie、密码或 metadata。
func (r *AccountSummaryRepository) GetOwnerID(ctx context.Context, accountID string) (int64, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return 0, validationErr
}
// ownerID、queryErr 保存数据库返回的账号所有者及查询错误。
ownerID, queryErr := r.store.Cookies.GetOwnerID(ctx, accountID)
return ownerID, normalizeAccountSummaryError(queryErr)
}
// StatusOwned 查询账号启用状态,并在状态读取前按用户复核账号归属。
func (r *AccountSummaryRepository) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
// validationErr 表示摘要数据库适配器尚未完成装配。
validationErr := r.validateCookies()
if validationErr != nil {
return false, validationErr
}
// _, ownershipErr 丢弃摘要内容,只保留状态查询前的归属结论。
if _, ownershipErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID); ownershipErr != nil {
return false, normalizeAccountSummaryError(ownershipErr)
}
// enabled、statusErr 保存数据库返回的状态及查询错误。
enabled, statusErr := r.store.Cookies.Status(ctx, accountID)
return enabled, normalizeAccountSummaryError(statusErr)
}
// ListAdminSummaries 查询管理员账号摘要并补充启用状态,不读取凭证字段。
func (r *AccountSummaryRepository) ListAdminSummaries(ctx context.Context) ([]accountapp.AdminAccountSummary, error) {
if r == nil || r.store == nil || r.store.Admin == nil || r.store.Cookies == nil {
return nil, errors.New("管理员账号摘要数据库适配器未初始化")
}
// records、queryErr 保存管理员账号摘要行及查询错误。
records, queryErr := r.store.Admin.ListCookies(ctx)
if queryErr != nil {
return nil, queryErr
}
// summaries 保存管理员端所需的非敏感账号摘要。
summaries := make([]accountapp.AdminAccountSummary, 0, len(records))
// record 表示当前待补充启用状态的管理员账号摘要。
for _, record := range records {
// enabled 表示当前账号的启用状态;数据库故障按停用处理以保持既有响应语义。
enabled := r.store.Cookies.GetStatus(ctx, record.ID)
summaries = append(summaries, accountapp.AdminAccountSummary{
ID: record.ID, UserID: record.UserID, Remark: record.Remark,
CreatedAt: record.CreatedAt, Owner: record.Owner, Enabled: enabled,
})
}
return summaries, nil
}
// validateCookies 检查账号摘要适配器是否拥有必要的数据库子仓储。
func (r *AccountSummaryRepository) validateCookies() error {
if r == nil || r.store == nil || r.store.Cookies == nil {
return errors.New("账号摘要数据库适配器未初始化")
}
return nil
}
// accountSummaryModel 将数据库摘要转换为不含敏感字段的应用模型。
func accountSummaryModel(record db.CookieSummary) accountapp.AccountSummary {
return accountapp.AccountSummary{
ID: record.ID, UserID: record.UserID, AutoConfirm: record.AutoConfirm,
Remark: record.Remark, PauseDuration: record.PauseDuration, PausedUntil: record.PausedUntil,
Username: record.Username, ShowBrowser: record.ShowBrowser, Nickname: record.Nickname,
AvatarURL: record.AvatarURL, LastRefreshAt: record.LastRefreshAt, LoginMethod: record.LoginMethod,
LastLoginAt: record.LastLoginAt, CreatedAt: record.CreatedAt,
}
}
// normalizeAccountSummaryError 将数据库所有权错误转换为应用层稳定错误。
func normalizeAccountSummaryError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, db.ErrNotFound) {
return accountapp.ErrNotFound
}
if errors.Is(err, db.ErrForbidden) {
return accountapp.ErrForbidden
}
return err
}
var _ accountapp.AccountSummaryRepository = (*AccountSummaryRepository)(nil)
var _ accountapp.AdminSummaryRepository = (*AccountSummaryRepository)(nil)
+129
View File
@@ -0,0 +1,129 @@
package adapter
import (
"context"
"errors"
"testing"
accountapp "xianyu-go/internal/application/account"
)
// TestAccountSummaryRepositoryRejectsMissingStore 验证账号摘要适配器缺少数据库时所有入口均快速失败。
func TestAccountSummaryRepositoryRejectsMissingStore(t *testing.T) {
// repository 是未装配数据库的账号摘要适配器。
repository := NewAccountSummaryRepository(nil)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// err 表示账号 ID 列表查询因缺少数据库依赖返回的装配错误。
if _, err := repository.ListOwnedIDs(ctx, 1); err == nil {
t.Fatal("缺少数据库时 ListOwnedIDs 不应成功")
}
// err 表示账号摘要列表查询因缺少数据库依赖返回的装配错误。
if _, err := repository.ListSummaries(ctx, 1); err == nil {
t.Fatal("缺少数据库时 ListSummaries 不应成功")
}
// err 表示单个账号摘要查询因缺少数据库依赖返回的装配错误。
if _, err := repository.GetOwnedSummary(ctx, 1, "cid"); err == nil {
t.Fatal("缺少数据库时 GetOwnedSummary 不应成功")
}
// err 表示账号所有权查询因缺少数据库依赖返回的装配错误。
if _, err := repository.ExistsOwned(ctx, 1, "cid"); err == nil {
t.Fatal("缺少数据库时 ExistsOwned 不应成功")
}
// err 表示账号所有者查询因缺少数据库依赖返回的装配错误。
if _, err := repository.GetOwnerID(ctx, "cid"); err == nil {
t.Fatal("缺少数据库时 GetOwnerID 不应成功")
}
// err 表示账号启用状态查询因缺少数据库依赖返回的装配错误。
if _, err := repository.StatusOwned(ctx, 1, "cid"); err == nil {
t.Fatal("缺少数据库时 StatusOwned 不应成功")
}
// err 表示管理员账号摘要查询因缺少数据库依赖返回的装配错误。
if _, err := repository.ListAdminSummaries(ctx); err == nil {
t.Fatal("缺少数据库时 ListAdminSummaries 不应成功")
}
}
// TestAccountSummaryRepositoryMapsNonSensitiveQueries 验证真实 SQLite 下摘要、所有权、状态和管理员列表的映射。
func TestAccountSummaryRepositoryMapsNonSensitiveQueries(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的账号摘要适配器。
repository := NewAccountSummaryRepository(store)
// ctx 是本测试共用的非取消数据库上下文。
ctx := context.Background()
// ids、idsErr 保存账号 ID 列表及查询错误。
ids, idsErr := repository.ListOwnedIDs(ctx, 1)
if idsErr != nil || len(ids) != 1 || ids[0] != "cid" {
t.Fatalf("账号 ID 列表异常 ids=%v err=%v", ids, idsErr)
}
// summaries、summariesErr 保存账号摘要列表及查询错误。
summaries, summariesErr := repository.ListSummaries(ctx, 1)
if summariesErr != nil || len(summaries) != 1 || summaries[0].ID != "cid" {
t.Fatalf("账号摘要异常 summaries=%+v err=%v", summaries, summariesErr)
}
// summary、summaryErr 保存单个账号摘要及查询错误。
summary, summaryErr := repository.GetOwnedSummary(ctx, 1, "cid")
if summaryErr != nil || summary.ID != "cid" || summary.UserID != 1 {
t.Fatalf("单个摘要异常 summary=%+v err=%v", summary, summaryErr)
}
// owned、ownedErr 保存本人账号的所有权结论。
owned, ownedErr := repository.ExistsOwned(ctx, 1, "cid")
if ownedErr != nil || !owned {
t.Fatalf("本人所有权异常 owned=%v err=%v", owned, ownedErr)
}
// ownerID、ownerErr 保存账号所有者查询结果。
ownerID, ownerErr := repository.GetOwnerID(ctx, "cid")
if ownerErr != nil || ownerID != 1 {
t.Fatalf("账号所有者异常 ownerID=%d err=%v", ownerID, ownerErr)
}
// enabled、statusErr 保存账号启用状态及查询错误。
enabled, statusErr := repository.StatusOwned(ctx, 1, "cid")
if statusErr != nil || !enabled {
t.Fatalf("账号状态异常 enabled=%v err=%v", enabled, statusErr)
}
// adminSummaries、adminErr 保存管理员账号摘要及查询错误。
adminSummaries, adminErr := repository.ListAdminSummaries(ctx)
if adminErr != nil || len(adminSummaries) != 1 || adminSummaries[0].ID != "cid" || !adminSummaries[0].Enabled {
t.Fatalf("管理员摘要异常 summaries=%+v err=%v", adminSummaries, adminErr)
}
}
// TestAccountSummaryRepositoryMapsOwnershipAndInfrastructureErrors 验证越权、缺失账号和数据库故障不会返回伪成功。
func TestAccountSummaryRepositoryMapsOwnershipAndInfrastructureErrors(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的账号摘要适配器。
repository := NewAccountSummaryRepository(store)
// ctx 是本测试共用的非取消数据库上下文。
ctx := context.Background()
// _, otherErr 保存第二个用户创建错误;用户主键随后从摘要查询得到。
_, otherErr := store.Users.Create(ctx, "other", "other@example.com", "pw")
if otherErr != nil {
t.Fatalf("创建第二用户失败: %v", otherErr)
}
// other、otherLookupErr 保存第二个用户及读取错误。
other, otherLookupErr := store.Users.GetByUsername(ctx, "other")
if otherLookupErr != nil {
t.Fatalf("读取第二用户失败: %v", otherLookupErr)
}
// wrongOwned、wrongOwnedErr 保存跨用户所有权查询结果。
wrongOwned, wrongOwnedErr := repository.ExistsOwned(ctx, other.ID, "cid")
if wrongOwnedErr != nil || wrongOwned {
t.Fatalf("跨用户所有权异常 owned=%v err=%v", wrongOwned, wrongOwnedErr)
}
// _, missingErr 验证缺失账号被转换为应用层稳定错误。
if _, missingErr := repository.GetOwnedSummary(ctx, 1, "missing"); !errors.Is(missingErr, accountapp.ErrNotFound) {
t.Fatalf("缺失账号错误=%v,期望=%v", missingErr, accountapp.ErrNotFound)
}
// closeErr 保存关闭数据库连接的资源释放错误。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// _, queryErr 验证数据库关闭后适配器透传基础设施错误。
if _, queryErr := repository.ListSummaries(ctx, 1); queryErr == nil {
t.Fatal("数据库关闭后不应伪装摘要读取成功")
}
}
+113
View File
@@ -0,0 +1,113 @@
package adapter
import (
"context"
"errors"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
)
// AccountTaskRepository 将账号任务数据库模型适配为应用层模型。
type AccountTaskRepository struct {
// store 保存账号任务持久化入口。
store *db.Store
}
// NewAccountTaskRepository 构造账号任务仓储适配器。
func NewAccountTaskRepository(store *db.Store) *AccountTaskRepository {
return &AccountTaskRepository{store: store}
}
// GetSettings 读取账号任务设置并移除数据库模型依赖。
func (r *AccountTaskRepository) GetSettings(ctx context.Context, accountID string) (automationapp.AccountTaskSettings, error) {
// validateErr 表示适配器缺少数据库任务仓储时的装配错误。
if validateErr := r.validate(); validateErr != nil {
return automationapp.AccountTaskSettings{}, validateErr
}
// settings、err 保存数据库设置及读取错误。
settings, err := r.store.AccountTasks.Get(ctx, accountID)
return accountTaskSettingsModel(settings), err
}
// SaveSettings 将应用层账号任务设置写入数据库。
func (r *AccountTaskRepository) SaveSettings(ctx context.Context, settings automationapp.AccountTaskSettings) error {
// validateErr 表示适配器缺少数据库任务仓储时的装配错误。
if validateErr := r.validate(); validateErr != nil {
return validateErr
}
return r.store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{
CookieID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent,
AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime,
LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt,
})
}
// ListRuns 读取账号任务运行记录并转换为应用层模型。
func (r *AccountTaskRepository) ListRuns(ctx context.Context, accountID string, limit int) ([]automationapp.AccountTaskRun, error) {
// validateErr 表示适配器缺少数据库任务仓储时的装配错误。
if validateErr := r.validate(); validateErr != nil {
return nil, validateErr
}
// runs、err 保存数据库运行记录及读取错误。
runs, err := r.store.AccountTasks.RecentRuns(ctx, accountID, limit)
if err != nil {
return nil, err
}
// result 保存转换后的应用层运行记录。
result := make([]automationapp.AccountTaskRun, 0, len(runs))
// run 是当前待转换的数据库运行记录。
for _, run := range runs {
result = append(result, automationapp.AccountTaskRun{
ID: run.ID, RunKey: run.RunKey, CookieID: 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, nil
}
// validate 检查账号任务数据库适配器是否具备必需的 Store 和子仓储。
func (r *AccountTaskRepository) validate() error {
if r == nil || r.store == nil || r.store.AccountTasks == nil {
return errors.New("账号任务数据库适配器未初始化")
}
return nil
}
// accountTaskSettingsModel 将数据库账号任务设置转换为应用模型。
func accountTaskSettingsModel(settings db.AccountTaskSettings) automationapp.AccountTaskSettings {
return automationapp.AccountTaskSettings{
CookieID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent,
AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime,
LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt,
}
}
// AccountTaskRunner 将自动化中心的执行结果适配为应用层摘要。
type AccountTaskRunner struct {
// center 执行账号评价和商品擦亮任务。
center *automation.Center
}
// NewAccountTaskRunner 构造账号任务执行适配器。
func NewAccountTaskRunner(center *automation.Center) *AccountTaskRunner {
return &AccountTaskRunner{center: center}
}
// RunAccountTask 执行任务并转换非敏感结果摘要。
func (r *AccountTaskRunner) RunAccountTask(ctx context.Context, accountID, taskType string) (automationapp.TaskSummary, error) {
if r == nil || r.center == nil {
return automationapp.TaskSummary{}, automationapp.ErrUnavailable
}
// summary、err 保存自动化中心结果及执行错误。
summary, err := r.center.RunAccountTask(ctx, accountID, taskType)
return automationapp.TaskSummary{
TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success,
Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message,
}, err
}
var _ automationapp.Repository = (*AccountTaskRepository)(nil)
var _ automationapp.Runner = (*AccountTaskRunner)(nil)
+16
View File
@@ -0,0 +1,16 @@
package adapter
import (
"context"
"testing"
)
// TestAccountTaskRepositoryRejectsMissingStore 验证账号任务数据库适配器不会因缺少 Store 而 panic。
func TestAccountTaskRepositoryRejectsMissingStore(t *testing.T) {
// repository 是未装配数据库的账号任务适配器。
repository := NewAccountTaskRepository(nil)
// _, err 保存缺少数据库时的明确错误。
if _, err := repository.GetSettings(context.Background(), "account-1"); err == nil {
t.Fatal("缺少 Store 时应返回错误")
}
}
+62
View File
@@ -0,0 +1,62 @@
package adapter
import (
"context"
"errors"
adminapp "xianyu-go/internal/application/admin"
"xianyu-go/internal/db"
)
// AdminRepository 将管理员数据库查询转换为非敏感应用模型。
type AdminRepository struct {
// store 保存管理员查询所需的数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// NewAdminRepository 构造管理员数据库适配器。
func NewAdminRepository(store *db.Store) *AdminRepository {
return &AdminRepository{store: store}
}
// ListUsers 查询用户摘要并丢弃密码及其他敏感字段。
func (r *AdminRepository) ListUsers(ctx context.Context) ([]adminapp.UserSummary, error) {
if r == nil || r.store == nil || r.store.Admin == nil {
return nil, errors.New("管理员查询适配器未初始化")
}
// rows、err 保存数据库用户摘要行及查询错误。
rows, err := r.store.Admin.ListUsers(ctx)
if err != nil {
return nil, err
}
// users 保存已脱敏的应用层用户摘要。
users := make([]adminapp.UserSummary, 0, len(rows))
// row 表示当前待转换的数据库用户摘要。
for _, row := range rows {
users = append(users, adminapp.UserSummary{ID: row.ID, Username: row.Username, Email: row.Email, IsActive: row.IsActive, IsAdmin: row.IsAdmin, CreatedAt: row.CreatedAt, CookieCount: row.CookieCount})
}
return users, nil
}
// DeleteUser 删除指定用户及其关联账号。
func (r *AdminRepository) DeleteUser(ctx context.Context, userID int64) error {
if r == nil || r.store == nil || r.store.Users == nil {
return errors.New("管理员删除适配器未初始化")
}
return r.store.Users.Delete(ctx, userID)
}
// Stats 查询数据库聚合统计并转换为应用模型。
func (r *AdminRepository) Stats(ctx context.Context) (adminapp.Stats, error) {
if r == nil || r.store == nil || r.store.Admin == nil {
return adminapp.Stats{}, errors.New("管理员统计适配器未初始化")
}
// stats、err 保存数据库聚合统计及查询错误。
stats, err := r.store.Admin.Stats(ctx)
if err != nil {
return adminapp.Stats{}, err
}
return adminapp.Stats{TotalUsers: stats.TotalUsers, TotalCookies: stats.TotalCookies, ActiveCookies: stats.ActiveCookies, TotalCards: stats.TotalCards, TotalKeywords: stats.TotalKeywords, TotalOrders: stats.TotalOrders}, nil
}
var _ adminapp.Repository = (*AdminRepository)(nil)
+46
View File
@@ -0,0 +1,46 @@
package adapter
import (
"context"
"testing"
)
// TestAdminRepositoryMapsUsersStatsAndDelete 验证管理员适配器只返回摘要并保留删除/统计语义。
func TestAdminRepositoryMapsUsersStatsAndDelete(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 保存本测试共用的数据库操作上下文。
ctx := context.Background()
// created、createErr 保存普通用户创建结果。
created, createErr := store.Users.Create(ctx, "admin-repository-user", "admin-repository@example.com", "password")
if createErr != nil || !created {
t.Fatalf("创建管理员适配器测试用户失败 created=%v err=%v", created, createErr)
}
// repository 保存绑定 SQLite Store 的管理员适配器。
repository := NewAdminRepository(store)
// users、usersErr 保存脱敏用户列表及错误。
users, usersErr := repository.ListUsers(ctx)
if usersErr != nil || len(users) < 2 {
t.Fatalf("用户列表查询异常 len=%d err=%v", len(users), usersErr)
}
// stats、statsErr 保存管理员统计及错误。
stats, statsErr := repository.Stats(ctx)
if statsErr != nil || stats.TotalUsers < 2 {
t.Fatalf("管理员统计异常 stats=%+v err=%v", stats, statsErr)
}
// targetID 保存待删除用户的数据库标识。
target, targetErr := store.Users.GetByUsername(ctx, "admin-repository-user")
if targetErr != nil || target == nil {
t.Fatalf("查询待删除用户失败 target=%v err=%v", target, targetErr)
}
// deleteErr 保存管理员删除操作的错误。
if deleteErr := repository.DeleteUser(ctx, target.ID); deleteErr != nil {
t.Fatalf("删除用户失败: %v", deleteErr)
}
// missingErr 保存缺失适配器依赖的错误。
missingErr := (*AdminRepository)(nil).DeleteUser(ctx, target.ID)
if missingErr == nil {
t.Fatal("空管理员适配器应拒绝删除")
}
}
+163
View File
@@ -0,0 +1,163 @@
package adapter
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"xianyu-go/internal/netguard"
)
// MaxAIModelsResponseBytes 限制远端模型目录响应大小,避免管理员配置的端点耗尽内存。
const MaxAIModelsResponseBytes = 4 << 20
// AIModelClient 通过管理员明确配置的端点读取 AI 模型目录。
type AIModelClient struct {
// newHTTPClient 允许测试替换端点客户端,同时生产默认使用受信任端点策略。
newHTTPClient func(baseURL string) (*http.Client, error)
}
// NewAIModelClient 构造 AI 模型目录适配器。
func NewAIModelClient() *AIModelClient {
// client 保存生产环境使用的模型目录客户端。
client := &AIModelClient{newHTTPClient: func(baseURL string) (*http.Client, error) {
return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second)
}}
return client
}
// Fetch 请求模型目录并只返回模型名称,不返回 API 密钥或原始响应内容。
func (c *AIModelClient) Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error) {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if baseURL == "" {
return nil, fmt.Errorf("AI API 地址为空")
}
if c == nil || c.newHTTPClient == nil {
return nil, fmt.Errorf("AI 模型客户端未初始化")
}
// req 是带有请求上下文的模型目录请求;API 密钥只存在于请求头。
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 是经过地址校验的出站客户端。
client, err := c.newHTTPClient(baseURL)
if err != nil {
return nil, fmt.Errorf("AI API 地址无效: %w", err)
}
// response 是远端模型目录 HTTP 响应。
response, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("读取模型失败: %w", err)
}
defer response.Body.Close()
// raw 是限制大小后读取的响应内容。
raw, err := ReadAIModelsBody(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fmt.Errorf("读取模型失败: HTTP %d %s", response.StatusCode, truncateAIModelBody(string(raw), 180))
}
// models、err 保存解析后的模型名称及解析错误。
models, err := ParseAIModels(raw)
if err != nil {
return nil, err
}
if len(models) == 0 {
return nil, fmt.Errorf("模型列表为空")
}
return models, nil
}
// ReadAIModelsBody 读取并限制远端模型目录响应。
func ReadAIModelsBody(reader io.Reader) ([]byte, error) {
// raw 是限制大小后读取的响应内容。
raw, err := io.ReadAll(io.LimitReader(reader, MaxAIModelsResponseBytes+1))
if err != nil {
return nil, err
}
if len(raw) > MaxAIModelsResponseBytes {
return nil, fmt.Errorf("模型列表响应超过 %d MiB", MaxAIModelsResponseBytes>>20)
}
return raw, nil
}
// ParseAIModels 从兼容 OpenAI 的多种响应形状提取去重模型名称。
func ParseAIModels(raw []byte) ([]string, error) {
// payload 是远端模型目录的通用 JSON 载荷。
var payload any
// err 表示远端模型目录 JSON 解析错误。
if err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("解析模型列表失败: %w", err)
}
// seen 保存已返回的模型名称,避免重复项污染下拉列表。
seen := make(map[string]bool)
// result 保存按远端出现顺序排列的模型名称。
var result []string
// addModel 将非空模型名称加入结果并去重。
addModel := func(value string) {
value = strings.TrimSpace(value)
if value == "" || seen[value] {
return
}
seen[value] = true
result = append(result, value)
}
// walk 递归解析 data、models、对象和字符串等兼容响应结构。
var walk func(any)
walk = func(value any) {
// typed 是当前 JSON 节点的具体类型。
switch typed := value.(type) {
case []any:
// item 是模型目录数组中的当前元素。
for _, item := range typed {
walk(item)
}
case map[string]any:
// id、ok 保存优先使用的模型标识及其类型判断结果。
if id, ok := typed["id"].(string); ok && id != "" {
addModel(id)
} else if // name、ok 保存模型名称回退值及其类型判断结果。
name, ok := typed["name"].(string); ok && name != "" {
addModel(name)
}
case string:
addModel(typed)
}
}
// root、ok 保存顶层对象及对象类型判断结果。
if root, ok := payload.(map[string]any); ok {
// data、ok 保存兼容 OpenAI 的 data 字段及存在性判断结果。
if data, ok := root["data"]; ok {
walk(data)
} else if // models、ok 保存兼容服务的 models 字段及存在性判断结果。
models, ok := root["models"]; ok {
walk(models)
}
} else {
walk(payload)
}
return result, nil
}
// truncateAIModelBody 截取错误响应,避免把超大远端正文写入日志或 HTTP 错误。
func truncateAIModelBody(value string, limit int) string {
value = strings.TrimSpace(value)
if len(value) <= limit {
return value
}
return value[:limit]
}
var _ interface {
Fetch(context.Context, string, string) ([]string, error)
} = (*AIModelClient)(nil)
+42
View File
@@ -0,0 +1,42 @@
package adapter
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestParseAIModelsSupportsOpenAIShapes 验证模型目录解析兼容 data、models 和名称回退结构。
func TestParseAIModelsSupportsOpenAIShapes(t *testing.T) {
// models、err 保存模型目录解析结果和错误。
models, err := ParseAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"name":"fallback"},{"id":"qwen-plus"}]}`))
if err != nil || len(models) != 2 || models[0] != "qwen-plus" || models[1] != "fallback" {
t.Fatalf("models=%v err=%v", models, err)
}
}
// TestAIModelClientFetchUsesHeaderAndBounds 验证模型请求只把密钥放入请求头并拒绝空模型列表。
func TestAIModelClientFetchUsesHeaderAndBounds(t *testing.T) {
// server 是返回固定模型目录的本地测试端点。
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.Header.Get("Authorization") != "Bearer test-secret" {
t.Error("authorization header was not forwarded")
}
_, _ = writer.Write([]byte(`{"models":["qwen-plus"]}`))
}))
defer server.Close()
// client 是替换了受信任端点 HTTP 工厂的测试客户端。
client := &AIModelClient{newHTTPClient: func(string) (*http.Client, error) { return &http.Client{}, nil }}
// models、err 保存模型请求结果和错误。
models, err := client.Fetch(context.Background(), server.URL, "test-secret")
if err != nil || len(models) != 1 || models[0] != "qwen-plus" {
t.Fatalf("models=%v err=%v", models, err)
}
// oversizedErr 表示超大模型响应被拒绝的错误。
_, oversizedErr := ReadAIModelsBody(strings.NewReader(strings.Repeat("x", MaxAIModelsResponseBytes+1)))
if oversizedErr == nil {
t.Fatal("oversized model response should fail")
}
}
+319
View File
@@ -0,0 +1,319 @@
package adapter
import (
"context"
"database/sql"
"strings"
analyticsapp "xianyu-go/internal/application/analytics"
"xianyu-go/internal/db"
)
// AnalyticsRepository 将 Store 的只读查询能力适配为订单分析应用 Port。
type AnalyticsRepository struct {
// store 保存数据库聚合入口,仅由该基础设施适配器访问。
store *db.Store
}
// NewAnalyticsRepository 构造订单分析查询适配器。
func NewAnalyticsRepository(store *db.Store) *AnalyticsRepository {
return &AnalyticsRepository{store: store}
}
// DashboardStats 返回用户范围内的仪表盘计数,不读取账号凭证字段。
func (r *AnalyticsRepository) DashboardStats(ctx context.Context, userID int64) (analyticsapp.DashboardStats, error) {
// stats 保存基础统计结果。
stats := analyticsapp.DashboardStats{}
// queries 保存用户范围内的固定计数查询及其目标字段。
queries := []struct {
// query 是当前统计项的 SQL。
query string
// target 是统计项写入结果的字段名称。
target string
}{
{query: `SELECT COUNT(*) FROM cookies WHERE user_id=?`, target: "cookies"},
{query: `SELECT COUNT(*) FROM cards WHERE user_id=?`, target: "cards"},
{query: `SELECT COUNT(*) FROM keywords k WHERE EXISTS (SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`, target: "keywords"},
{query: `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=?)`, target: "orders"},
}
// item 是当前遍历的仪表盘统计项。
for _, item := range queries {
// count 是当前统计项的数据库结果。
var count int64
if // err 是当前统计项查询错误。
err := r.store.Analytics.QueryRowContext(ctx, item.query, userID).Scan(&count); err != nil {
return analyticsapp.DashboardStats{}, err
}
switch item.target {
case "cookies":
stats.TotalCookies = count
case "cards":
stats.TotalCards = count
case "keywords":
stats.TotalKeywords = count
case "orders":
stats.TotalOrders = count
}
}
// activeCookies 是没有明确禁用记录的账号数量。
var activeCookies int64
if // err 是活跃账号统计查询错误。
err := r.store.Analytics.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 analyticsapp.DashboardStats{}, err
}
stats.ActiveCookies = activeCookies
return stats, nil
}
// AvailableCardStock 计算启用数据卡密组中的非空卡密行数,不向应用层传递卡密内容。
func (r *AnalyticsRepository) AvailableCardStock(ctx context.Context, userID int64) (int64, error) {
// rows 是用户数据卡密组的最小查询结果。
// rows、err 是用户数据卡密组查询结果及错误。
rows, err := r.store.DB.QueryContext(ctx, `SELECT enabled, type, data_content FROM cards WHERE user_id=?`, userID)
if err != nil {
return 0, err
}
defer rows.Close()
// stock 是可用卡密行数。
var stock int64
for rows.Next() {
// enabled 是当前卡密组是否启用的可空数据库字段。
var enabled sql.NullInt64
// cardType 是当前卡密组的业务类型。
var cardType sql.NullString
// dataContent 是当前数据卡密组的换行分隔内容。
var dataContent sql.NullString
if // err 是当前卡密组读取错误。
err := rows.Scan(&enabled, &cardType, &dataContent); err != nil {
return 0, err
}
if !enabled.Valid || enabled.Int64 == 0 || !cardType.Valid || cardType.String != "data" {
continue
}
// line 是数据卡密组中的单行卡密。
for _, line := range strings.Split(strings.ReplaceAll(dataContent.String, "\r\n", "\n"), "\n") {
if strings.TrimSpace(line) != "" {
stock++
}
}
}
return stock, rows.Err()
}
// QueryRevenue 返回订单收益汇总。
func (r *AnalyticsRepository) QueryRevenue(ctx context.Context, filter analyticsapp.Filter) (analyticsapp.RevenueStats, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, clean, amountFilter := r.orderScope(filter, "amount")
// stats 是数据库返回的收益聚合值。
var stats analyticsapp.RevenueStats
// err 是收益汇总查询错误。
err := r.store.Analytics.QueryRowContext(ctx, `
SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0),
COALESCE(AVG(`+clean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id)
FROM orders `+where+amountFilter, args...).Scan(
&stats.TotalOrders, &stats.TotalAmount, &stats.AvgAmount, &stats.UniqueBuyers, &stats.UniqueItems)
return stats, err
}
// QueryDaily 返回按订单读取的日期聚合原始记录。
func (r *AnalyticsRepository) QueryDaily(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.DailyRecord, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, _, amountFilter := r.orderScope(filter, "amount")
// rows、err 是日期聚合查询结果及错误。
rows, err := r.store.Analytics.QueryContext(ctx, `SELECT order_id,amount,created_at FROM orders `+where+amountFilter, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// records 是订单日期聚合原始记录。
records := make([]analyticsapp.DailyRecord, 0)
for rows.Next() {
// record 是当前订单的原始统计字段。
var record analyticsapp.DailyRecord
if // err 是当前日期记录读取错误。
err := rows.Scan(&record.OrderID, &record.Amount, &record.CreatedAt); err != nil {
return nil, err
}
records = append(records, record)
}
return records, rows.Err()
}
// QueryStatus 返回按原始订单状态聚合的结果。
func (r *AnalyticsRepository) QueryStatus(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.StatusRecord, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, clean, amountFilter := r.orderScope(filter, "amount")
// rows、err 是状态聚合查询结果及错误。
rows, err := r.store.Analytics.QueryContext(ctx, `
SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0)
FROM orders `+where+amountFilter+`
GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// records 是数据库按原始状态返回的聚合记录。
records := make([]analyticsapp.StatusRecord, 0)
for rows.Next() {
// record 是当前状态的聚合字段。
var record analyticsapp.StatusRecord
if // err 是当前状态记录读取错误。
err := rows.Scan(&record.Status, &record.Count, &record.Amount); err != nil {
return nil, err
}
records = append(records, record)
}
return records, rows.Err()
}
// QueryCity 返回按收货城市聚合的结果。
func (r *AnalyticsRepository) QueryCity(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.CityRecord, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, clean, amountFilter := r.orderScope(filter, "amount")
// rows、err 是城市聚合查询结果及错误。
rows, err := r.store.Analytics.QueryContext(ctx, `
SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0)
FROM orders `+where+amountFilter+`
AND receiver_city IS NOT NULL AND receiver_city != ''
GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// records 是数据库按城市返回的聚合记录。
records := make([]analyticsapp.CityRecord, 0)
for rows.Next() {
// record 是当前城市的聚合字段。
var record analyticsapp.CityRecord
if // err 是当前城市记录读取错误。
err := rows.Scan(&record.City, &record.Count, &record.Amount); err != nil {
return nil, err
}
records = append(records, record)
}
return records, rows.Err()
}
// QueryItem 返回按商品标识聚合的结果。
func (r *AnalyticsRepository) QueryItem(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.ItemRecord, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, clean, amountFilter := r.orderScope(filter, "amount")
// rows、err 是商品聚合查询结果及错误。
rows, err := r.store.Analytics.QueryContext(ctx, `
SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0), COALESCE(AVG(`+clean+`),0)
FROM orders `+where+amountFilter+`
AND item_id IS NOT NULL AND item_id != ''
GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// records 是数据库按商品返回的聚合记录。
records := make([]analyticsapp.ItemRecord, 0)
for rows.Next() {
// record 是当前商品的聚合字段。
var record analyticsapp.ItemRecord
if // err 是当前商品记录读取错误。
err := rows.Scan(&record.ItemID, &record.Count, &record.TotalAmount, &record.AvgAmount); err != nil {
return nil, err
}
records = append(records, record)
}
return records, rows.Err()
}
// CountValidOrders 返回有效订单总数。
func (r *AnalyticsRepository) CountValidOrders(ctx context.Context, filter analyticsapp.Filter) (int, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, _, amountFilter := r.orderScope(filter, "orders.amount")
// total 是数据库返回的有效订单数量。
var total int
// err 是有效订单总数查询错误。
err := r.store.Analytics.QueryRowContext(ctx, `SELECT COUNT(*) FROM orders `+where+amountFilter, args...).Scan(&total)
return total, err
}
// ListValidOrders 返回有效订单分页明细。
func (r *AnalyticsRepository) ListValidOrders(ctx context.Context, filter analyticsapp.Filter, limit, offset int) ([]analyticsapp.ValidOrderRecord, error) {
// where、args、clean 和 amountFilter 是当前方言的订单范围条件。
where, args, _, amountFilter := r.orderScope(filter, "orders.amount")
args = append(args, limit, offset)
// rows、err 是有效订单分页查询结果及错误。
rows, err := r.store.Analytics.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
`+where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// records 是当前分页的有效订单字段。
records := make([]analyticsapp.ValidOrderRecord, 0)
for rows.Next() {
// record 是当前订单的明细字段。
var record analyticsapp.ValidOrderRecord
if // err 是当前有效订单记录读取错误。
err := rows.Scan(&record.OrderID, &record.ItemID, &record.ItemTitle, &record.ItemDetail, &record.BuyerID, &record.Quantity, &record.Amount, &record.Status, &record.CookieID, &record.CreatedAt); err != nil {
return nil, err
}
records = append(records, record)
}
return records, rows.Err()
}
// orderScope 构造订单查询的用户、日期、状态和金额过滤条件。
func (r *AnalyticsRepository) orderScope(filter analyticsapp.Filter, amountColumn string) (string, []any, string, string) {
// conditions 保存 SQL WHERE 条件片段。
conditions := []string{"orders.deleted_at IS NULL"}
// args 保存条件对应的参数值。
args := make([]any, 0, len(filter.Statuses)+3)
if filter.StartAt != "" {
conditions = append(conditions, "orders.created_at >= ?")
args = append(args, filter.StartAt)
}
if filter.EndBefore != "" {
conditions = append(conditions, "orders.created_at < ?")
args = append(args, filter.EndBefore)
}
if filter.UserID != 0 {
conditions = append(conditions, "EXISTS (SELECT 1 FROM cookies WHERE cookies.id = orders.cookie_id AND cookies.user_id = ?)")
args = append(args, filter.UserID)
}
if len(filter.Statuses) > 0 {
// placeholders 是状态条件需要的占位符列表。
placeholders := make([]string, len(filter.Statuses))
// index 是当前状态占位符的序号。
for index := range filter.Statuses {
placeholders[index] = "?"
args = append(args, filter.Statuses[index])
}
conditions = append(conditions, "orders.order_status IN ("+strings.Join(placeholders, ",")+")")
}
// where 是带 WHERE 前缀和尾随空格的条件文本。
where := "WHERE " + strings.Join(conditions, " AND ") + " "
// clean 是当前数据库方言清洗金额文本的表达式。
clean := amountExpression(r.store.Dialect, amountColumn)
return where, args, clean, " AND " + clean + " IS NOT NULL"
}
// amountExpression 返回当前数据库方言的安全金额表达式。
func amountExpression(dialect db.Dialect, column string) string {
// 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`
}
}
// 确保基础设施适配器实现完整的订单分析应用 Port。
var _ analyticsapp.Repository = (*AnalyticsRepository)(nil)
@@ -0,0 +1,151 @@
package adapter
import (
"context"
"errors"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// AuthenticationRepository 将用户密码与会话数据库操作适配为账号认证应用端口。
type AuthenticationRepository struct {
// store 保存数据库聚合入口;用户密码只在适配器调用期间参与校验或写入。
store *db.Store
}
// NewAuthenticationRepository 构造认证数据库适配器。
func NewAuthenticationRepository(store *db.Store) *AuthenticationRepository {
return &AuthenticationRepository{store: store}
}
// IsSystemInitialized 查询数据库中是否已经存在管理员账号。
func (r *AuthenticationRepository) IsSystemInitialized(ctx context.Context) (bool, error) {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return false, validationErr
}
return r.store.Users.IsSystemInitialized(ctx)
}
// InitializeAdmin 创建或重置管理员账号,保持命令行初始化入口的兼容语义。
func (r *AuthenticationRepository) InitializeAdmin(ctx context.Context, email, password string) (bool, error) {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return false, validationErr
}
// existing、lookupErr 保存现有管理员和查询错误;初始化调用方会在外层先做未初始化检查。
existing, lookupErr := r.store.Users.GetAdmin(ctx)
if lookupErr != nil && !errors.Is(lookupErr, db.ErrNotFound) {
return false, lookupErr
}
if existing != nil {
// updated、updateErr 保存既有管理员密码更新结果。
updated, updateErr := r.store.Users.UpdatePassword(ctx, existing.Username, password)
if updateErr != nil {
return false, updateErr
}
if !updated {
return false, errors.New("管理员存在但密码未更新")
}
return false, r.store.Users.SetAdmin(ctx, existing.Username)
}
// created、createErr 保存新管理员创建结果。
created, createErr := r.store.Users.Create(ctx, "admin", email, password)
if createErr != nil {
return false, createErr
}
if !created {
return false, errors.New("创建管理员失败:用户名或邮箱可能已存在")
}
return true, r.store.Users.SetAdmin(ctx, "admin")
}
// UsernameByEmail 按邮箱取得登录用户名,不向应用层暴露密码哈希等完整用户字段。
func (r *AuthenticationRepository) UsernameByEmail(ctx context.Context, email string) (string, error) {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return "", validationErr
}
// user、lookupErr 保存邮箱查询结果;仅提取登录用户名后立即丢弃数据库模型。
user, lookupErr := r.store.Users.GetByEmail(ctx, email)
if lookupErr != nil {
return "", lookupErr
}
if user == nil {
return "", db.ErrNotFound
}
return user.Username, nil
}
// VerifyPassword 校验密码并转换为不含敏感字段的应用身份。
func (r *AuthenticationRepository) VerifyPassword(ctx context.Context, username, password string) (accountapp.AuthUser, bool, error) {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return accountapp.AuthUser{}, false, validationErr
}
// user、matched、verifyErr 保存数据库密码校验结果;密码哈希不跨出本方法。
user, matched, verifyErr := r.store.Users.VerifyAndUpgrade(ctx, username, password)
if verifyErr != nil {
if errors.Is(verifyErr, db.ErrPasswordMismatch) {
return accountapp.AuthUser{}, false, accountapp.ErrPasswordMismatch
}
return accountapp.AuthUser{}, false, verifyErr
}
if !matched || user == nil {
return accountapp.AuthUser{}, false, nil
}
return accountapp.AuthUser{ID: user.ID, Username: user.Username, IsAdmin: user.IsAdmin}, true, nil
}
// UpdatePassword 更新密码并撤销该用户全部旧会话。
func (r *AuthenticationRepository) UpdatePassword(ctx context.Context, username, password string) (bool, error) {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return false, validationErr
}
return r.store.Users.UpdatePassword(ctx, username, password)
}
// UpdateCredentials 原子更新登录用户名及可选密码,并转换用户名冲突错误。
func (r *AuthenticationRepository) UpdateCredentials(ctx context.Context, userID int64, username, password string) error {
// validationErr 表示认证用户仓储是否已经完成装配。
validationErr := r.validateUsers()
if validationErr != nil {
return validationErr
}
// updateErr 保存登录凭据写入及事务提交结果。
updateErr := r.store.Users.UpdateCredentials(ctx, userID, username, password)
if updateErr != nil {
if errors.Is(updateErr, db.ErrUsernameTaken) {
return accountapp.ErrUsernameTaken
}
return updateErr
}
return nil
}
// CreateSession 为认证成功的应用身份创建数据库会话。
func (r *AuthenticationRepository) CreateSession(ctx context.Context, user accountapp.AuthUser) (string, error) {
if r == nil || r.store == nil || r.store.Sessions == nil {
return "", errors.New("认证会话数据库适配器未初始化")
}
// dbUser 是仅供会话仓储写入的非敏感数据库用户投影。
dbUser := &db.User{ID: user.ID, Username: user.Username, IsAdmin: user.IsAdmin}
return r.store.Sessions.Create(ctx, dbUser)
}
// validateUsers 检查认证适配器是否已装配用户仓储。
func (r *AuthenticationRepository) validateUsers() error {
if r == nil || r.store == nil || r.store.Users == nil {
return errors.New("认证用户数据库适配器未初始化")
}
return nil
}
var _ accountapp.AuthenticationRepository = (*AuthenticationRepository)(nil)
@@ -0,0 +1,117 @@
package adapter
import (
"context"
"errors"
"path/filepath"
"testing"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/db"
)
// TestAuthenticationRepositoryMapsLoginAndPasswordOperations 验证认证端口在 SQLite 中映射登录、会话和改密行为。
func TestAuthenticationRepositoryMapsLoginAndPasswordOperations(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的认证适配器。
repository := NewAuthenticationRepository(store)
// ctx 是本测试数据库操作共用的非取消上下文。
ctx := context.Background()
// setAdminErr 保存测试管理员标记结果,确保初始化状态与夹具语义一致。
if setAdminErr := store.Users.SetAdmin(ctx, "admin"); setAdminErr != nil {
t.Fatalf("标记管理员失败: %v", setAdminErr)
}
// initialized、initializedErr 保存系统初始化状态查询结果。
initialized, initializedErr := repository.IsSystemInitialized(ctx)
if initializedErr != nil || !initialized {
t.Fatalf("初始化状态异常 initialized=%v err=%v", initialized, initializedErr)
}
// username、usernameErr 保存邮箱映射结果。
username, usernameErr := repository.UsernameByEmail(ctx, "a@e.com")
if usernameErr != nil || username != "admin" {
t.Fatalf("邮箱映射异常 username=%q err=%v", username, usernameErr)
}
// user、matched、verifyErr 保存正确密码校验结果。
user, matched, verifyErr := repository.VerifyPassword(ctx, "admin", "pw")
if verifyErr != nil || !matched || user.ID == 0 || !user.IsAdmin {
t.Fatalf("正确密码校验异常 user=%+v matched=%v err=%v", user, matched, verifyErr)
}
// sessionID、sessionErr 保存认证成功后的会话写入结果。
sessionID, sessionErr := repository.CreateSession(ctx, user)
if sessionErr != nil || sessionID == "" {
t.Fatalf("会话写入异常 session=%q err=%v", sessionID, sessionErr)
}
// _, wrongMatched、wrongErr 保存错误密码的稳定失败语义。
_, wrongMatched, wrongErr := repository.VerifyPassword(ctx, "admin", "wrong")
if wrongMatched || !errors.Is(wrongErr, accountapp.ErrPasswordMismatch) {
t.Fatalf("错误密码映射异常 matched=%v err=%v", wrongMatched, wrongErr)
}
// updated、updateErr 保存管理员密码更新结果。
updated, updateErr := repository.UpdatePassword(ctx, "admin", "new-password")
if updateErr != nil || !updated {
t.Fatalf("密码更新异常 updated=%v err=%v", updated, updateErr)
}
// _, newMatched、newVerifyErr 验证新密码生效。
_, newMatched, newVerifyErr := repository.VerifyPassword(ctx, "admin", "new-password")
if newVerifyErr != nil || !newMatched {
t.Fatalf("新密码校验异常 matched=%v err=%v", newMatched, newVerifyErr)
}
}
// TestAuthenticationRepositoryMapsInitializationAndUsernameConflicts 验证管理员初始化和用户名冲突映射。
func TestAuthenticationRepositoryMapsInitializationAndUsernameConflicts(t *testing.T) {
// database、dialect、openErr 保存全新 SQLite 数据库的打开结果。
database, dialect, openErr := db.Open(context.Background(), filepath.Join(t.TempDir(), "auth.db"))
if openErr != nil {
t.Fatalf("打开数据库失败: %v", openErr)
}
defer database.Close()
// store 是全新数据库的 repository 聚合入口。
store := db.NewStore(database, dialect)
// repository 是绑定全新数据库的认证适配器。
repository := NewAuthenticationRepository(store)
// ctx 是本测试数据库操作共用的非取消上下文。
ctx := context.Background()
// created、createErr 保存首次管理员初始化结果。
created, createErr := repository.InitializeAdmin(ctx, "admin@example.com", "password")
if createErr != nil || !created {
t.Fatalf("首次初始化异常 created=%v err=%v", created, createErr)
}
// createdAgain、resetErr 保存已初始化管理员的兼容重置结果。
createdAgain, resetErr := repository.InitializeAdmin(ctx, "ignored@example.com", "new-password")
if resetErr != nil || createdAgain {
t.Fatalf("重复初始化异常 created=%v err=%v", createdAgain, resetErr)
}
// _, otherCreateErr 验证重复用户名的数据库结果不会伪装成认证成功。
if _, otherCreateErr := store.Users.Create(ctx, "other", "other@example.com", "password"); otherCreateErr != nil {
t.Fatalf("创建冲突测试用户失败: %v", otherCreateErr)
}
// admin、adminErr 保存管理员用户查询结果。
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
if adminErr != nil {
t.Fatalf("查询管理员失败: %v", adminErr)
}
// conflictErr 保存将管理员改成已占用用户名的结果。
conflictErr := repository.UpdateCredentials(ctx, admin.ID, "other", "")
if !errors.Is(conflictErr, accountapp.ErrUsernameTaken) {
t.Fatalf("用户名冲突映射异常: %v", conflictErr)
}
}
// TestAuthenticationRepositoryRejectsMissingDependencies 验证认证适配器缺少数据库时所有入口均快速失败。
func TestAuthenticationRepositoryRejectsMissingDependencies(t *testing.T) {
// repository 是未装配数据库的认证适配器。
repository := NewAuthenticationRepository(nil)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// initializedErr 保存缺少用户仓储时的初始化状态错误。
if _, initializedErr := repository.IsSystemInitialized(ctx); initializedErr == nil {
t.Fatal("缺少用户仓储时不应返回初始化成功")
}
// sessionErr 保存缺少会话仓储时的会话创建错误。
if _, sessionErr := repository.CreateSession(ctx, accountapp.AuthUser{ID: 1, Username: "admin"}); sessionErr == nil {
t.Fatal("缺少会话仓储时不应返回会话成功")
}
}
@@ -0,0 +1,31 @@
package adapter
import (
"context"
"errors"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/db"
)
// AutomationCredentialWakeRepository 将自动化任务唤醒 Port 适配为数据库仓储。
type AutomationCredentialWakeRepository struct {
// store 保存自动化任务数据库仓储入口。
store *db.Store
}
// NewAutomationCredentialWakeRepository 构造自动化凭证唤醒数据库适配器。
func NewAutomationCredentialWakeRepository(store *db.Store) *AutomationCredentialWakeRepository {
return &AutomationCredentialWakeRepository{store: store}
}
// WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的自动化任务。
func (r *AutomationCredentialWakeRepository) WakeCredentialBlocked(ctx context.Context, accountID string) error {
if r == nil || r.store == nil || r.store.Automation == nil {
return errors.New("自动化任务存储未初始化")
}
return r.store.Automation.WakeCredentialBlocked(ctx, accountID)
}
// 确保数据库适配器覆盖凭证恢复唤醒应用 Port。
var _ automationapp.CredentialWakeRepository = (*AutomationCredentialWakeRepository)(nil)
@@ -0,0 +1,16 @@
package adapter
import (
"context"
"testing"
)
// TestAutomationCredentialWakeRepositoryRejectsMissingStore 验证缺失数据库时返回明确错误。
func TestAutomationCredentialWakeRepositoryRejectsMissingStore(t *testing.T) {
// repository 是未装配数据库的自动化凭证唤醒适配器。
repository := NewAutomationCredentialWakeRepository(nil)
// err 保存缺失数据库依赖时的适配器错误。
if err := repository.WakeCredentialBlocked(context.Background(), "acc1"); err == nil {
t.Fatal("缺少数据库时不应伪装唤醒成功")
}
}
+221
View File
@@ -0,0 +1,221 @@
package adapter
import (
"context"
"errors"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/db"
)
// AutomationRepository 将 Store 的自动化异常查询与 resolve 能力适配为应用 Port。
type AutomationRepository struct {
// store 保存数据库聚合入口,仅由该基础设施适配器访问。
store *db.Store
}
// NewAutomationRepository 构造自动化异常应用 Port 的数据库适配器。
func NewAutomationRepository(store *db.Store) *AutomationRepository {
return &AutomationRepository{store: store}
}
// ListIssues 查询并转换当前用户可见的自动化异常摘要。
func (r *AutomationRepository) ListIssues(ctx context.Context, userID int64) ([]automationapp.RunIssue, []automationapp.DeferredIssue, error) {
// runIssues、deferredIssues、err 保存数据库异常摘要和查询错误。
runIssues, deferredIssues, err := r.store.Automation.ListIssues(ctx, userID)
if err != nil {
return nil, nil, mapAutomationIssueError(err)
}
// runs 是不携带数据库模型的运行异常摘要列表。
runs := make([]automationapp.RunIssue, 0, len(runIssues))
// runIssue 是当前待转换的数据库运行异常记录。
for _, runIssue := range runIssues {
runs = append(runs, automationapp.RunIssue{
ID: runIssue.ID, CookieID: runIssue.CookieID, OrderID: runIssue.OrderID,
TriggerType: runIssue.TriggerType, ErrorMessage: runIssue.ErrorMessage,
IssueKind: runIssue.IssueKind, AllowedResolutions: runIssue.AllowedResolutions,
ActionCursor: runIssue.ActionCursor, SentCount: runIssue.SentCount, UpdatedAt: runIssue.UpdatedAt,
})
}
// tasks 是不携带数据库模型的延期异常摘要列表。
tasks := make([]automationapp.DeferredIssue, 0, len(deferredIssues))
// deferredIssue 是当前待转换的数据库延期异常记录。
for _, deferredIssue := range deferredIssues {
tasks = append(tasks, automationapp.DeferredIssue{
ID: deferredIssue.ID, CookieID: deferredIssue.CookieID, TriggerType: deferredIssue.TriggerType,
ErrorMessage: deferredIssue.ErrorMessage, AttemptCount: deferredIssue.AttemptCount, UpdatedAt: deferredIssue.UpdatedAt,
})
}
return runs, tasks, nil
}
// ResolveRunIssue 按用户归属执行异常运行人工处理,并归一化未找到错误。
func (r *AutomationRepository) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error {
return mapAutomationIssueError(r.store.Automation.ResolveRunIssue(ctx, userID, runID, resolution))
}
// ResolveDeferredIssue 按用户归属重试或删除死信延期任务,并归一化未找到错误。
func (r *AutomationRepository) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error {
return mapAutomationIssueError(r.store.Automation.ResolveDeferredIssue(ctx, userID, taskID, retry))
}
// mapAutomationIssueError 将数据库未找到错误转换为应用层错误,避免 Port 暴露数据库包。
func mapAutomationIssueError(err error) error {
if errors.Is(err, db.ErrNotFound) {
return automationapp.ErrNotFound
}
return err
}
// ListForUser 返回用户全部自动化规则的应用模型。
func (r *AutomationRepository) ListForUser(ctx context.Context, userID int64) ([]automationapp.Rule, error) {
// rules、err 保存数据库规则列表及查询失败原因。
rules, err := r.store.Automation.ListForUser(ctx, userID)
if err != nil {
return nil, err
}
return automationRulesModel(rules), nil
}
// ListPageForUser 返回用户自动化规则分页及总数。
func (r *AutomationRepository) ListPageForUser(ctx context.Context, filter automationapp.RuleFilter) ([]automationapp.Rule, int, error) {
// rules、total、err 保存分页规则、总数及数据库查询失败原因。
rules, total, err := r.store.Automation.ListPageForUser(ctx, db.AutomationRuleListFilter{
UserID: filter.UserID, CookieID: filter.CookieID, TriggerType: filter.TriggerType,
Enabled: filter.Enabled, Search: filter.Search, Limit: filter.Limit, Offset: filter.Offset,
})
if err != nil {
return nil, 0, err
}
return automationRulesModel(rules), total, nil
}
// CountByTriggerForUser 返回用户规则触发类型统计。
func (r *AutomationRepository) CountByTriggerForUser(ctx context.Context, filter automationapp.RuleFilter) (map[string]int, error) {
return r.store.Automation.CountByTriggerForUser(ctx, db.AutomationRuleListFilter{
UserID: filter.UserID, CookieID: filter.CookieID, TriggerType: filter.TriggerType,
Enabled: filter.Enabled, Search: filter.Search,
})
}
// Create 将应用层规则输入转换为数据库模型并创建规则。
func (r *AutomationRepository) Create(ctx context.Context, input automationapp.RuleInput) (int64, error) {
return r.store.Automation.Create(ctx, automationRuleInputDB(input))
}
// EnsurePublishRule 将发布自动化规则输入转换为数据库模型并执行幂等创建。
func (r *AutomationRepository) EnsurePublishRule(ctx context.Context, input automationapp.RuleInput) error {
// databaseInput 保存发布自动化规则对应的数据库写入模型。
databaseInput := automationRuleInputDB(input)
// exists、err 保存同一发布规则的存在状态及查询错误。
exists, err := r.store.Automation.ExistsPublishRule(ctx, databaseInput)
if err != nil {
return err
}
if exists {
return nil
}
// _, err 保存首次创建发布自动化规则的结果。
_, err = r.store.Automation.Create(ctx, databaseInput)
return err
}
// Update 将应用层规则输入转换为数据库模型并更新规则。
func (r *AutomationRepository) Update(ctx context.Context, userID, ruleID int64, input automationapp.RuleInput) error {
// err 保存数据库更新失败原因,随后转换为应用层错误。
err := r.store.Automation.Update(ctx, userID, ruleID, automationRuleInputDB(input))
return mapAutomationRuleError(err)
}
// Delete 删除用户拥有的规则并转换数据库错误边界。
func (r *AutomationRepository) Delete(ctx context.Context, userID, ruleID int64) error {
return mapAutomationRuleError(r.store.Automation.Delete(ctx, userID, ruleID))
}
// OwnsAccount 返回账号是否属于指定用户。
func (r *AutomationRepository) OwnsAccount(ctx context.Context, userID int64, accountID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, accountID)
}
// OwnsItem 返回商品是否属于指定用户账号。
func (r *AutomationRepository) OwnsItem(ctx context.Context, userID int64, accountID, itemID string) (bool, error) {
// owned、err 保存账号归属查询结果及失败原因。
owned, err := r.store.Cookies.ExistsOwned(ctx, userID, accountID)
if err != nil || !owned {
return false, err
}
// _, err 保存按账号和商品双键读取结果;只有未找到才转换为业务上的不归属。
_, err = r.store.Items.Get(ctx, accountID, itemID)
if errors.Is(err, db.ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// GetCard 返回用户拥有的卡密组类型,不将卡密内容传入应用层。
func (r *AutomationRepository) GetCard(ctx context.Context, userID, cardID int64) (automationapp.CardInfo, error) {
// card、err 保存卡密组摘要及读取失败原因;卡密正文不会进入应用层。
card, err := r.store.Cards.Get(ctx, cardID)
if errors.Is(err, db.ErrNotFound) || (err == nil && (card == nil || card.UserID != userID)) {
return automationapp.CardInfo{}, automationapp.ErrRuleNotFound
}
if err != nil {
return automationapp.CardInfo{}, err
}
return automationapp.CardInfo{Type: card.Type}, nil
}
// automationRulesModel 将数据库规则列表转换为应用模型。
func automationRulesModel(rules []db.AutomationRule) []automationapp.Rule {
// result 保存从数据库模型转换出的应用规则列表。
result := make([]automationapp.Rule, 0, len(rules))
// rule 是当前待转换的数据库规则。
for _, rule := range rules {
// actions 保存当前规则转换后的应用动作列表。
actions := make([]automationapp.Action, 0, len(rule.Actions))
// action 是当前待转换的数据库动作。
for _, action := range rule.Actions {
actions = append(actions, automationapp.Action{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})
}
result = append(result, automationapp.Rule{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 result
}
// automationRuleInputDB 将应用规则输入转换为数据库写入模型。
func automationRuleInputDB(input automationapp.RuleInput) db.AutomationRuleInput {
// actions 保存转换后的数据库动作写入模型。
actions := make([]db.AutomationActionInput, 0, len(input.Actions))
// action 是当前待转换的应用动作。
for _, action := range input.Actions {
actions = append(actions, db.AutomationActionInput{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 db.AutomationRuleInput{UserID: input.UserID, CookieID: input.CookieID, ItemID: input.ItemID, Name: input.Name,
TriggerType: input.TriggerType, Enabled: input.Enabled, Priority: input.Priority, ConfigJSON: input.ConfigJSON, Actions: actions}
}
// mapAutomationRuleError 将数据库规则错误转换为应用层错误。
func mapAutomationRuleError(err error) error {
if errors.Is(err, db.ErrNotFound) {
return automationapp.ErrRuleNotFound
}
if errors.Is(err, db.ErrAutomationRunActive) {
return automationapp.ErrRuleActive
}
return err
}
// automationRepositoryCompileCheck 确保数据库适配器完整实现应用 Port。
var _ automationapp.IssueRepository = (*AutomationRepository)(nil)
var _ automationapp.RuleRepository = (*AutomationRepository)(nil)
var _ automationapp.RuleOwnership = (*AutomationRepository)(nil)
var _ automationapp.PublishRuleRepository = (*AutomationRepository)(nil)
@@ -0,0 +1,104 @@
package adapter
import (
"context"
"errors"
"testing"
automationapp "xianyu-go/internal/application/automation"
"xianyu-go/internal/db"
)
// TestAutomationRepositoryOwnershipMapsNotFound 验证资源缺失只表现为不归属,不泄露数据库模型错误。
func TestAutomationRepositoryOwnershipMapsNotFound(t *testing.T) {
// store 是当前适配器测试使用的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的自动化规则适配器。
repository := NewAutomationRepository(store)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// owned、ownedErr 保存不存在商品的归属判断结果。
owned, ownedErr := repository.OwnsItem(ctx, 1, "cid", "missing-item")
if owned || ownedErr != nil {
t.Fatalf("缺失商品应返回 false,nil,owned=%v err=%v", owned, ownedErr)
}
// cardInfo、cardErr 保存不存在卡密组的最小应用摘要及错误。
cardInfo, cardErr := repository.GetCard(ctx, 1, 999999)
if cardInfo != (automationapp.CardInfo{}) || !errors.Is(cardErr, automationapp.ErrRuleNotFound) {
t.Fatalf("缺失卡密组应映射为应用未找到,info=%+v err=%v", cardInfo, cardErr)
}
}
// TestAutomationRepositoryOwnershipPropagatesDatabaseErrors 验证数据库不可用时不会伪装成归属失败。
func TestAutomationRepositoryOwnershipPropagatesDatabaseErrors(t *testing.T) {
// store 是当前适配器测试使用的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的自动化规则适配器。
repository := NewAutomationRepository(store)
// ctx 是数据库关闭后调用适配器的非取消上下文。
ctx := context.Background()
// closeErr 表示提前关闭测试数据库时的资源释放错误。
closeErr := store.DB.Close()
if closeErr != nil {
t.Fatal(closeErr)
}
// _, itemErr 保存商品归属查询透传的数据库错误。
_, itemErr := repository.OwnsItem(ctx, 1, "cid", "item-1")
if itemErr == nil {
t.Fatal("数据库关闭后商品归属查询应返回错误")
}
// _, cardErr 保存卡密组查询透传的数据库错误。
_, cardErr := repository.GetCard(ctx, 1, 1)
if cardErr == nil || errors.Is(cardErr, db.ErrNotFound) || errors.Is(cardErr, automationapp.ErrRuleNotFound) {
t.Fatalf("数据库关闭后卡密查询应保留底层错误,err=%v", cardErr)
}
}
// TestAutomationRepositoryEnsurePublishRuleIsIdempotent 验证发布自动化规则只创建一次。
func TestAutomationRepositoryEnsurePublishRuleIsIdempotent(t *testing.T) {
// store 是当前适配器测试使用的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的自动化规则适配器。
repository := NewAutomationRepository(store)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// input 是代表发布成功后自动发货的规则输入。
input := automationapp.RuleInput{UserID: 1, CookieID: "cid", ItemID: "item-1", Name: "付款后自动发货 - 商品", TriggerType: automationapp.TriggerOrderPaid, Enabled: true, Priority: 100, ConfigJSON: "{}", Actions: []automationapp.ActionInput{{ActionType: automationapp.ActionConfirmShipment, Enabled: true, SortOrder: 1}}}
// firstErr 保存第一次幂等准备的错误。
firstErr := repository.EnsurePublishRule(ctx, input)
if firstErr != nil {
t.Fatal(firstErr)
}
// secondErr 保存第二次幂等准备的错误。
secondErr := repository.EnsurePublishRule(ctx, input)
if secondErr != nil {
t.Fatal(secondErr)
}
// rules、matchErr 保存按发布规则唯一条件查询到的规则。
rules, matchErr := store.Automation.Match(ctx, input.CookieID, input.ItemID, input.TriggerType)
if matchErr != nil || len(rules) != 1 {
t.Fatalf("幂等准备应只保留一条规则,rules=%+v err=%v", rules, matchErr)
}
}
// TestAutomationRepositoryEnsurePublishRulePropagatesDatabaseError 验证数据库故障不会被发布规则适配器吞掉。
func TestAutomationRepositoryEnsurePublishRulePropagatesDatabaseError(t *testing.T) {
// store 是当前适配器测试使用的 SQLite 存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的自动化规则适配器。
repository := NewAutomationRepository(store)
// closeErr 表示提前关闭测试数据库时的资源释放错误。
closeErr := store.DB.Close()
if closeErr != nil {
t.Fatal(closeErr)
}
// err 保存关闭数据库后执行幂等准备的错误。
err := repository.EnsurePublishRule(context.Background(), automationapp.RuleInput{UserID: 1, CookieID: "account-1", ItemID: "item-1", Name: "规则", TriggerType: automationapp.TriggerOrderPaid})
if err == nil {
t.Fatal("数据库关闭后应返回发布规则持久化错误")
}
}
+127
View File
@@ -0,0 +1,127 @@
package adapter
import (
"context"
"errors"
cardsapp "xianyu-go/internal/application/cards"
"xianyu-go/internal/db"
)
// CardsRepository 将卡券数据库仓储适配为应用层消费者定义的 CRUD Port。
type CardsRepository struct {
// store 保存数据库聚合入口,但只通过 Cards 子仓储访问卡券数据。
store *db.Store
}
// NewCardsRepository 构造卡券数据库适配器;装配缺失会在方法调用时返回错误。
func NewCardsRepository(store *db.Store) *CardsRepository {
return &CardsRepository{store: store}
}
// ListForUser 查询指定用户的卡券组并转换为应用模型。
func (r *CardsRepository) ListForUser(ctx context.Context, userID int64) ([]cardsapp.Card, error) {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return nil, err
}
// records 是数据库仓储按倒序返回的卡券完整记录。
records, err := r.store.Cards.AllForUser(ctx, userID)
if err != nil {
return nil, err
}
// result 是与数据库模型解耦的应用卡券列表。
result := make([]cardsapp.Card, 0, len(records))
// record 是当前待转换的数据库卡券记录。
for _, record := range records {
result = append(result, cardApplicationModel(record))
}
return result, nil
}
// Get 查询单个卡券组,并把数据库缺失错误映射为应用层稳定错误。
func (r *CardsRepository) Get(ctx context.Context, cardID int64) (cardsapp.Card, error) {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return cardsapp.Card{}, err
}
// record 是数据库返回的完整卡券记录。
record, err := r.store.Cards.Get(ctx, cardID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return cardsapp.Card{}, cardsapp.ErrNotFound
}
return cardsapp.Card{}, err
}
return cardApplicationModel(*record), nil
}
// Create 将已校验的应用卡券模型转换为数据库模型并返回新标识。
func (r *CardsRepository) Create(ctx context.Context, card cardsapp.Card) (int64, error) {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return 0, err
}
// record 是仅在适配器内存在的数据库写入模型。
record := cardDatabaseModel(card)
return r.store.Cards.Create(ctx, &record)
}
// Update 将应用层可编辑字段写入数据库,不向上层暴露数据库模型。
func (r *CardsRepository) Update(ctx context.Context, card cardsapp.Card) error {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return err
}
// record 是仅在适配器内存在的数据库更新模型。
record := cardDatabaseModel(card)
return r.store.Cards.Update(ctx, &record)
}
// Delete 删除指定卡券组,并原样返回数据库约束或连接错误。
func (r *CardsRepository) Delete(ctx context.Context, cardID int64) error {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return err
}
return r.store.Cards.Delete(ctx, cardID)
}
// AppendData 将 data 卡券组的逐行库存追加能力适配到应用 Port。
func (r *CardsRepository) AppendData(ctx context.Context, cardID int64, content string) (int, error) {
// err 表示卡券适配器依赖缺失时的装配错误。
if err := r.validate(); err != nil {
return 0, err
}
return r.store.Cards.AppendBatchData(ctx, cardID, content)
}
// validate 检查卡券适配器是否具备 Store 与 Cards 子仓储。
func (r *CardsRepository) validate() error {
if r == nil || r.store == nil || r.store.Cards == nil {
return errors.New("卡券数据库适配器未初始化")
}
return nil
}
// cardApplicationModel 将数据库卡券记录转换为基础设施无关的应用模型。
func cardApplicationModel(record db.CardFull) cardsapp.Card {
return cardsapp.Card{
ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig,
TextContent: record.TextContent, DataContent: record.DataContent, ImageURL: record.ImageURL,
Description: record.Description, Enabled: record.Enabled, DelaySeconds: record.DelaySeconds,
IsMultiSpec: record.IsMultiSpec, SpecName: record.SpecName, SpecValue: record.SpecValue, UserID: record.UserID,
}
}
// cardDatabaseModel 将应用卡券模型转换为数据库仓储要求的写入模型。
func cardDatabaseModel(card cardsapp.Card) db.CardFull {
return db.CardFull{
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
}
}
var _ cardsapp.Repository = (*CardsRepository)(nil)
+121
View File
@@ -0,0 +1,121 @@
package adapter
import (
"context"
"errors"
"testing"
cardsapp "xianyu-go/internal/application/cards"
)
// TestCardsRepositoryCRUDMapping 验证 SQLite 卡券 CRUD 与应用模型之间的完整字段映射。
func TestCardsRepositoryCRUDMapping(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是待验证的卡券数据库适配器。
repository := NewCardsRepository(store)
// ctx 是本测试全部数据库操作使用的非取消上下文。
ctx := context.Background()
// owner 是测试模板中创建的卡券所有者。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// input 是覆盖全部持久化字段的应用卡券模型。
input := cardsapp.Card{
Name: "库存卡", Type: "data", APIConfig: "legacy", TextContent: "text", DataContent: "A\nB",
ImageURL: "https://example.invalid/card.png", Description: "description", Enabled: true,
DelaySeconds: 12, IsMultiSpec: true, SpecName: "颜色", SpecValue: "蓝", UserID: owner.ID,
}
// cardID、createErr 保存创建结果。
cardID, createErr := repository.Create(ctx, input)
if createErr != nil || cardID <= 0 {
t.Fatalf("创建卡券失败 id=%d err=%v", cardID, createErr)
}
// got、getErr 保存详情查询结果。
got, getErr := repository.Get(ctx, cardID)
if getErr != nil {
t.Fatal(getErr)
}
input.ID = cardID
if got != input {
t.Fatalf("详情字段映射不匹配 got=%+v want=%+v", got, input)
}
// listed、listErr 保存按用户隔离的列表结果。
listed, listErr := repository.ListForUser(ctx, owner.ID)
if listErr != nil || len(listed) != 1 || listed[0] != input {
t.Fatalf("列表字段映射不匹配 listed=%+v err=%v", listed, listErr)
}
got.Name = "更新后"
got.Enabled = false
// updateErr 表示更新卡券组时的数据库错误。
if updateErr := repository.Update(ctx, got); updateErr != nil {
t.Fatal(updateErr)
}
// updated、updatedErr 保存更新后的详情。
updated, updatedErr := repository.Get(ctx, cardID)
if updatedErr != nil || updated.Name != "更新后" || updated.Enabled {
t.Fatalf("更新结果异常 card=%+v err=%v", updated, updatedErr)
}
// deleteErr 表示删除卡券组时的数据库错误。
if deleteErr := repository.Delete(ctx, cardID); deleteErr != nil {
t.Fatal(deleteErr)
}
// missingErr 表示删除后再次读取卡券组的应用层未找到错误。
if _, missingErr := repository.Get(ctx, cardID); !errors.Is(missingErr, cardsapp.ErrNotFound) {
t.Fatalf("删除后应映射为应用层未找到,err=%v", missingErr)
}
}
// TestCardsRepositoryAppendDataMapping 验证卡券适配器把追加库存结果和内容写入数据库。
func TestCardsRepositoryAppendDataMapping(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是待验证的卡券数据库适配器。
repository := NewCardsRepository(store)
// ctx 是本测试数据库操作使用的非取消上下文。
ctx := context.Background()
// owner、ownerErr 保存测试模板中的卡券所有者及查询错误。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// cardID、createErr 保存 data 卡券组标识及创建错误。
cardID, createErr := repository.Create(ctx, cardsapp.Card{Name: "库存卡", Type: "data", DataContent: "A\n", UserID: owner.ID})
if createErr != nil {
t.Fatal(createErr)
}
// added、appendErr 保存适配器返回的有效新增行数及错误。
added, appendErr := repository.AppendData(ctx, cardID, "B\n\nC")
if appendErr != nil || added != 2 {
t.Fatalf("追加结果异常 added=%d err=%v", added, appendErr)
}
// got、getErr 保存追加后的卡券记录及读取错误。
got, getErr := repository.Get(ctx, cardID)
if getErr != nil || got.DataContent != "A\n\nB\n\nC" {
t.Fatalf("追加内容未正确映射 card=%+v err=%v", got, getErr)
}
}
// TestCardsRepositoryPropagatesInfrastructureErrors 验证数据库不可用时不会伪装成卡券缺失。
func TestCardsRepositoryPropagatesInfrastructureErrors(t *testing.T) {
// store 是随后主动关闭数据库连接的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定已关闭数据库的卡券适配器。
repository := NewCardsRepository(store)
// closeErr 表示主动关闭测试数据库连接时的资源释放错误。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// err 表示关闭数据库后读取卡券组的底层错误。
if _, err := repository.Get(context.Background(), 1); err == nil || errors.Is(err, cardsapp.ErrNotFound) {
t.Fatalf("数据库故障应原样返回,err=%v", err)
}
// err 表示缺少 Store 时的适配器装配错误。
if _, err := NewCardsRepository(nil).ListForUser(context.Background(), 1); err == nil {
t.Fatal("缺少 Store 时应返回装配错误")
}
}
@@ -0,0 +1,24 @@
package adapter
import (
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/db"
)
// ChatSessionFromApplication 将聊天应用会话转换为 legacy 聊天领域写入模型。
// 转换只包含会话展示字段,不携带 Cookie、Token 或其他账号秘密。
func ChatSessionFromApplication(session chatapp.Session) db.ChatSession {
return dbChatSession(session)
}
// ChatMessagesFromDB 将 legacy 聊天领域消息转换为应用层非敏感消息模型。
// 数据库模型只在 adapter 内部出现,调用方获得的结果不暴露存储层类型。
func ChatMessagesFromDB(messages []db.ChatMessage) []chatapp.Message {
// result 保存转换后的应用层消息列表。
result := make([]chatapp.Message, 0, len(messages))
// message 表示当前待转换的 legacy 聊天消息。
for _, message := range messages {
result = append(result, chatApplicationMessage(&message))
}
return result
}
@@ -0,0 +1,47 @@
package adapter
import (
"reflect"
"testing"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/db"
)
// TestChatSessionFromApplicationKeepsNonSensitiveFields 验证会话转换只复制非敏感展示字段。
func TestChatSessionFromApplicationKeepsNonSensitiveFields(t *testing.T) {
// session 保存应用层聊天会话摘要。
session := chatapp.Session{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", BuyerAvatar: "avatar", ItemID: "item-1", ItemTitle: "商品", LastMessage: "你好", LastMessageAt: 42, UnreadCount: 3}
// converted 保存转换后的 legacy 聊天会话模型。
converted := ChatSessionFromApplication(session)
// expected 保存应由领域仓储接收的非敏感会话字段。
expected := db.ChatSession{CookieID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", BuyerAvatar: "avatar", ItemID: "item-1", ItemTitle: "商品", LastMessage: "你好", LastMessageAt: 42, UnreadCount: 3}
if !reflect.DeepEqual(converted, expected) {
t.Fatalf("聊天会话转换异常: got=%+v want=%+v", converted, expected)
}
}
// TestChatMessagesFromDBKeepsMessageContract 验证数据库消息转换为应用消息时完整保留 API 所需字段。
func TestChatMessagesFromDBKeepsMessageContract(t *testing.T) {
// messages 保存 legacy 聊天仓储返回的消息模型。
messages := []db.ChatMessage{{ID: 7, CookieID: "account-1", ChatID: "chat-1", MessageKey: "key-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家", MessageType: "text", Content: "你好", Status: "received", SentAt: 99}}
// converted 保存不再暴露数据库模型的应用层消息。
converted := ChatMessagesFromDB(messages)
if len(converted) != 1 {
t.Fatalf("消息数量异常: got=%d", len(converted))
}
// expected 保存应用层消息字段。
expected := chatapp.Message{ID: 7, AccountID: "account-1", ChatID: "chat-1", MessageKey: "key-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家", MessageType: "text", Content: "你好", Status: "received", SentAt: 99}
if !reflect.DeepEqual(converted[0], expected) {
t.Fatalf("聊天消息转换异常: got=%+v want=%+v", converted[0], expected)
}
}
// TestChatMessagesFromDBHandlesEmptyInput 验证空消息页转换后保持可安全遍历的空切片。
func TestChatMessagesFromDBHandlesEmptyInput(t *testing.T) {
// converted 保存空 legacy 消息列表转换结果。
converted := ChatMessagesFromDB(nil)
if converted == nil || len(converted) != 0 {
t.Fatalf("空消息转换应返回非 nil 空切片: %#v", converted)
}
}
+134
View File
@@ -0,0 +1,134 @@
package adapter
import (
"context"
"errors"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// chatRepository 将数据库聊天仓储和账号归属查询适配为聊天应用端口。
type chatRepository struct {
// store 保存数据库聚合入口,仅在本适配器内执行聊天窄查询。
store *db.Store
}
// NewChatRepository 创建聊天历史应用服务使用的数据库适配器。
func NewChatRepository(store *db.Store) chatapp.Repository {
if store == nil || store.Chats == nil || store.Cookies == nil {
return nil
}
return chatRepository{store: store}
}
// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。
func (r chatRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) {
// rows 和 err 保存数据库消息记录及查询错误。
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 chatRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) {
// rows 和 err 保存数据库会话记录及查询错误。
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
}
// DeleteEmptySessions 删除没有有效消息的聊天会话壳。
func (r chatRepository) DeleteEmptySessions(ctx context.Context, accountID string) error {
return r.store.Chats.DeleteEmptySessions(ctx, accountID)
}
// UpdateSessionIdentity 更新会话的买家身份缓存。
func (r chatRepository) UpdateSessionIdentity(ctx context.Context, accountID, chatID, buyerID, buyerName, buyerAvatar string) error {
return r.store.Chats.UpdateSessionIdentity(ctx, accountID, chatID, buyerID, buyerName, buyerAvatar)
}
// ExistsOwned 判断账号是否归属于指定用户,只返回非敏感存在性。
func (r chatRepository) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, accountID)
}
// MarkRead 将用户拥有的聊天会话未读数归零,不读取或解密账号凭证。
func (r chatRepository) MarkRead(ctx context.Context, userID int64, accountID, chatID string) error {
return r.store.Chats.MarkRead(ctx, userID, accountID, chatID)
}
// chatIdentityResolver 在适配器内读取 Cookie 并调用平台身份查询接口。
type chatIdentityResolver struct {
// store 提供账号凭证读取能力,明文只在本次平台调用期间存在。
store *db.Store
// clientProvider 返回当前可注入的 MTOP 客户端,便于运行时替换和测试。
clientProvider func() mtop.Client
}
// NewChatIdentityResolver 创建聊天身份查询适配器。
func NewChatIdentityResolver(store *db.Store, clientProvider func() mtop.Client) chatapp.IdentityResolver {
if store == nil || store.Cookies == nil || clientProvider == nil {
return nil
}
return chatIdentityResolver{store: store, clientProvider: clientProvider}
}
// Resolve 查询聊天买家展示身份;Cookie 和平台客户端均不会离开适配器。
func (r chatIdentityResolver) Resolve(ctx context.Context, accountID, chatID string) (chatapp.Identity, error) {
// cookies 和 err 保存平台调用需要的短暂凭证及读取错误,不得写入日志或响应。
cookies, err := r.store.Cookies.GetValue(ctx, accountID)
if err != nil {
return chatapp.Identity{}, err
}
// client 保存当前 MTOP 客户端。
client := r.clientProvider()
// fetcher 和 supported 保存身份查询能力及接口支持情况。
fetcher, supported := client.(interface {
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
})
if !supported {
return chatapp.Identity{}, errors.New("当前 MTOP 客户端不支持聊天身份查询")
}
// info 和 err 保存平台返回的非敏感身份及查询错误。
info, err := fetcher.FetchChatUserInfo(ctx, cookies, chatID)
if err != nil {
return chatapp.Identity{}, err
}
if info == nil {
return chatapp.Identity{}, nil
}
return chatapp.Identity{BuyerName: info.Nickname, BuyerAvatar: info.AvatarURL}, nil
}
// 确保数据库聊天适配器覆盖应用层会话端口的全部能力。
var _ chatapp.SessionRepository = chatRepository{}
// 确保聊天身份适配器覆盖应用层平台身份端口。
var _ chatapp.IdentityResolver = chatIdentityResolver{}
+145
View File
@@ -0,0 +1,145 @@
package adapter
import (
"context"
"errors"
"testing"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// fakeChatUploadClient 只实现聊天图片上传能力,用于隔离平台网络请求。
type fakeChatUploadClient struct {
// mtop.Client 保留其余平台能力占位,测试只关注图片上传方法。
mtop.Client
// upload 保存模拟平台返回的图片结果。
upload *mtop.ChatImageUpload
// err 保存模拟平台上传错误。
err error
}
// UploadChatImage 返回预设图片结果或错误,不记录传入 Cookie。
func (c fakeChatUploadClient) UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) {
return c.upload, c.err
}
// fakeChatIdentityClient 只实现聊天身份查询,其余 MTOP 能力由嵌入接口占位。
type fakeChatIdentityClient struct {
// mtop.Client 保留未涉及本切片的 MTOP 能力占位。
mtop.Client
// info 保存模拟平台返回的买家展示身份。
info *mtop.ChatUserInfo
}
// FetchChatUserInfo 返回预设聊天身份,并记录适配器已能调用动态能力。
func (c fakeChatIdentityClient) FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) {
return c.info, nil
}
// TestChatRepositoryMapsSessionMaintenance 验证聊天数据库适配器覆盖列表、清理、身份和归属端口。
func TestChatRepositoryMapsSessionMaintenance(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试数据库操作使用的非取消上下文。
ctx := context.Background()
// repository 是聊天应用层会话端口的数据库实现。
repository := NewChatRepository(store)
// owner 是模板账号的所有者。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// session 是待写入数据库并转换回应用模型的非敏感会话。
session := db.ChatSession{CookieID: "cid", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", LastMessage: "你好", LastMessageAt: 10}
// saveErr 表示写入测试会话时的数据库错误。
if saveErr := store.Chats.UpsertSession(ctx, session); saveErr != nil {
t.Fatal(saveErr)
}
// port 是经类型断言确认的完整聊天维护端口。
port, ok := repository.(chatapp.SessionRepository)
if !ok {
t.Fatal("聊天适配器未覆盖 SessionRepository")
}
// listed 和 listErr 保存应用层会话列表及转换错误。
listed, listErr := port.ListSessions(ctx, owner.ID, "cid", 20)
if listErr != nil || len(listed) != 1 || listed[0].BuyerName != "买家" {
t.Fatalf("会话列表映射异常 listed=%+v err=%v", listed, listErr)
}
// owned 和 ownershipErr 保存账号归属查询结果。
owned, ownershipErr := port.ExistsOwned(ctx, owner.ID, "cid")
if ownershipErr != nil || !owned {
t.Fatalf("账号归属映射异常 owned=%v err=%v", owned, ownershipErr)
}
// updateErr 保存会话身份缓存写入错误。
if updateErr := port.UpdateSessionIdentity(ctx, "cid", "chat-1", "buyer-1", "新名称", "avatar"); updateErr != nil {
t.Fatal(updateErr)
}
// refreshed 和 refreshedErr 保存身份缓存写入后的会话列表。
refreshed, refreshedErr := port.ListSessions(ctx, owner.ID, "cid", 20)
if refreshedErr != nil || refreshed[0].BuyerName != "新名称" || refreshed[0].BuyerAvatar != "avatar" {
t.Fatalf("身份缓存未更新 refreshed=%+v err=%v", refreshed, refreshedErr)
}
// emptyErr 保存删除无消息会话壳的结果。
if emptyErr := port.DeleteEmptySessions(ctx, "cid"); emptyErr != nil {
t.Fatal(emptyErr)
}
}
// TestChatIdentityResolverKeepsCredentialsInsideAdapter 验证身份适配器只向应用层返回展示字段。
func TestChatIdentityResolverKeepsCredentialsInsideAdapter(t *testing.T) {
// store 是包含测试账号 Cookie 的临时数据库。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// client 是返回非敏感身份的测试 MTOP 客户端。
client := fakeChatIdentityClient{info: &mtop.ChatUserInfo{Nickname: "买家新名", AvatarURL: "https://example.invalid/avatar"}}
// resolver 是读取 Cookie 并调用测试平台客户端的聊天身份适配器。
resolver := NewChatIdentityResolver(store, func() mtop.Client { return client })
// identity 和 resolveErr 保存适配器转换后的身份及查询错误。
identity, resolveErr := resolver.Resolve(context.Background(), "cid", "chat-1")
if resolveErr != nil || identity.BuyerName != "买家新名" || identity.BuyerAvatar == "" {
t.Fatalf("身份映射异常 identity=%+v err=%v", identity, resolveErr)
}
}
// TestChatSendingAdaptersRejectUnavailableDependencies 验证实时聊天适配器的未装配错误分支。
func TestChatSendingAdaptersRejectUnavailableDependencies(t *testing.T) {
// outgoingErr 保存未装配聊天领域服务时的稳定应用错误。
_, outgoingErr := NewChatOutgoingRepository(nil).CreateOutgoing(context.Background(), chatapp.Session{}, "文本")
if !errors.Is(outgoingErr, chatapp.ErrUnavailable) {
t.Fatalf("nil outgoing service error=%v", outgoingErr)
}
// senderProvider 是未装配账号管理器的在线发送适配器。
senderProvider := NewChatSenderProvider(nil)
// sender、ok 保存未装配管理器时返回的发送器和存在性标记。
if sender, ok := senderProvider.Sender("account-1"); ok || sender != nil {
t.Fatalf("nil sender provider returned sender=%v ok=%v", sender, ok)
}
// uploadErr 保存未提供平台客户端时的稳定应用错误。
_, uploadErr := NewChatImageUploader(nil, nil, nil).UploadChatImage(context.Background(), "account-1", "a.jpg", "image/jpeg", []byte("image"))
if !errors.Is(uploadErr, chatapp.ErrUnavailable) {
t.Fatalf("nil image client error=%v", uploadErr)
}
}
// TestChatImageUploaderRejectsUnsupportedAndEmptyPlatformResults 验证图片上传适配器不会吞掉平台能力缺失或空结果。
func TestChatImageUploaderRejectsUnsupportedAndEmptyPlatformResults(t *testing.T) {
// store 是包含测试 Cookie 的临时数据库,凭证只在适配器调用期间读取。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// unsupportedErr 保存客户端缺少图片上传能力时的稳定错误。
_, unsupportedErr := NewChatImageUploader(store, func() mtop.Client { return fakeChatIdentityClient{} }, nil).UploadChatImage(context.Background(), "cid", "a.jpg", "image/jpeg", []byte("image"))
if !errors.Is(unsupportedErr, chatapp.ErrUnavailable) {
t.Fatalf("unsupported image client error=%v", unsupportedErr)
}
// emptyErr 保存平台返回空图片结果时的发送错误。
_, emptyErr := NewChatImageUploader(store, func() mtop.Client { return fakeChatUploadClient{} }, nil).UploadChatImage(context.Background(), "cid", "a.jpg", "image/jpeg", []byte("image"))
if !errors.Is(emptyErr, chatapp.ErrSend) {
t.Fatalf("empty image result error=%v", emptyErr)
}
}
var _ chatapp.SessionRepository = chatRepository{}
var _ chatapp.IdentityResolver = chatIdentityResolver{}
+221
View File
@@ -0,0 +1,221 @@
package adapter
import (
"context"
"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"
)
// chatOutgoingRepository 将聊天领域服务适配为应用层外发消息端口。
type chatOutgoingRepository struct {
// service 保存聊天消息幂等写入和实时事件发布能力。
service *domainchat.Service
}
// NewChatSendingApplication 装配聊天历史、实时发送、图片上传和身份补全端口。
func NewChatSendingApplication(domainService *domainchat.Service, store *db.Store, manager *account.Manager, clientProvider func() mtop.Client) *chatapp.Service {
return chatapp.NewWithSending(
NewChatRepository(store),
NewChatOutgoingRepository(domainService),
NewChatSenderProvider(manager),
NewChatImageUploader(store, clientProvider, manager),
NewChatIdentityResolver(store, clientProvider),
)
}
// NewChatOutgoingRepository 创建聊天外发消息的领域适配器。
func NewChatOutgoingRepository(service *domainchat.Service) chatapp.OutgoingRepository {
return chatOutgoingRepository{service: service}
}
// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。
func (r chatOutgoingRepository) 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, dbChatSession(session), text)
return chatApplicationMessage(message), err
}
// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。
func (r chatOutgoingRepository) 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, dbChatSession(session), messageType, content)
return chatApplicationMessage(message), err
}
// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。
func (r chatOutgoingRepository) 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 chatApplicationMessage(message), err
}
// dbChatSession 将应用层会话摘要转换为领域层写入模型,不携带账号凭证。
func dbChatSession(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,
}
}
// chatApplicationMessage 将领域消息转换为应用层非敏感模型;空指针保持零值。
func chatApplicationMessage(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,
}
}
// chatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。
type chatSenderProvider struct {
// manager 保存当前进程内的账号运行时管理器。
manager *account.Manager
}
// NewChatSenderProvider 创建按账号解析在线发送器的适配器。
func NewChatSenderProvider(manager *account.Manager) chatapp.SenderProvider {
return chatSenderProvider{manager: manager}
}
// Sender 返回指定账号的在线发送能力;账号不存在或运行时未装配时返回 false。
func (p chatSenderProvider) 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 chatSender{sender: sender}, true
}
// chatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。
type chatSender struct {
// sender 保存账号运行时提供的最小消息发送能力。
sender automation.MessageSender
}
// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。
func (s chatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error {
if s.sender == nil {
return chatapp.ErrUnavailable
}
return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text)
}
// SendImage 发送图片并将应用层幂等键传递给运行时接口。
func (s chatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error {
if s.sender == nil {
return chatapp.ErrUnavailable
}
return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID)
}
// chatCredentialRepository 将 Cookie 读取与写回限制在平台适配器内。
type chatCredentialRepository struct {
// store 保存数据库聚合入口,仅在适配器内读取和更新明文 Cookie。
store *db.Store
}
// getCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。
func (r chatCredentialRepository) 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 chatCredentialRepository) 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)
}
// chatImageUploader 将 MTOP 图片上传和凭证刷新适配为聊天应用端口。
type chatImageUploader struct {
// clientProvider 返回当前可注入的 MTOP 客户端,便于运行时替换和测试。
clientProvider func() mtop.Client
// credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。
credentials chatCredentialRepository
// manager 负责将刷新后的凭证同步到在线运行时。
manager *account.Manager
}
// NewChatImageUploader 创建聊天图片上传适配器;平台客户端和数据库依赖由调用方注入。
func NewChatImageUploader(store *db.Store, clientProvider func() mtop.Client, manager *account.Manager) chatapp.ImageUploader {
return chatImageUploader{clientProvider: clientProvider, credentials: chatCredentialRepository{store: store}, manager: manager}
}
// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。
func (u chatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) {
if u.clientProvider == nil {
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
}
// cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。
cookieValue, err := u.credentials.getCookieValue(ctx, accountID)
if err != nil {
return chatapp.ImageUpload{}, err
}
// client 保存当前可用的 MTOP 客户端。
client := u.clientProvider()
// uploader、ok 保存 MTOP 图片上传能力及接口支持情况。
uploader, ok := client.(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
}
// 编译期确认聊天实时适配器覆盖应用层定义的全部能力。
var (
_ chatapp.OutgoingRepository = chatOutgoingRepository{}
_ chatapp.SenderProvider = chatSenderProvider{}
_ chatapp.Sender = chatSender{}
_ chatapp.ImageUploader = chatImageUploader{}
)
+42
View File
@@ -0,0 +1,42 @@
package adapter
import (
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
// AccountIDFromCookie 从平台 Cookie 中提取扫码结果使用的账号标识;解析失败返回空字符串。
func AccountIDFromCookie(cookies string) string {
return protocol.TransCookies(cookies)["unb"]
}
// CookieSnapshotsFromResult 将扫码服务结果中的浏览器快照转换为应用层模型,避免 Server 依赖 Cookie 实现类型。
func CookieSnapshotsFromResult(result map[string]any) ([]accountapp.CookieSnapshot, bool) {
// raw 保存扫码结果中的原始 Cookie 快照;exists 表示结果是否提供该字段。
raw, exists := result["cookie_snapshot"]
if !exists {
return nil, false
}
// snapshot 保存平台 Cookie 快照;ok 表示其类型符合浏览器适配器约定。
snapshot, ok := raw.([]cookierefresh.BrowserCookie)
if !ok || snapshot == nil {
return nil, false
}
// normalized 保存去重、归一化后的 Cookie 快照。
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
// converted 保存脱离浏览器实现类型的应用层快照。
converted := make([]accountapp.CookieSnapshot, 0, len(normalized))
// cookie 表示当前待转换的浏览器 Cookie,明文只在适配器转换期间存在。
for _, cookie := range normalized {
converted = append(converted, 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,
})
}
return converted, true
}
+15
View File
@@ -0,0 +1,15 @@
package adapter
import "testing"
// TestAccountIDFromCookie 验证扫码 Cookie 中账号标识的解析及缺失字段行为。
func TestAccountIDFromCookie(t *testing.T) {
// got 是从完整 Cookie 字符串提取出的平台账号标识。
if got := AccountIDFromCookie("sid=value; unb=account-1; foo=bar"); got != "account-1" {
t.Fatalf("账号标识解析错误: %q", got)
}
// got 是缺少 unb 字段时的空账号标识结果。
if got := AccountIDFromCookie("sid=value"); got != "" {
t.Fatalf("缺少 unb 时应返回空字符串: %q", got)
}
}
+79
View File
@@ -0,0 +1,79 @@
package adapter
import (
"context"
"errors"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// CookieSession 是一次平台请求流程使用的 Cookie 会话实现别名;Server 通过本适配器访问它,避免直接依赖平台包。
type CookieSession = mtop.CookieSession
// BrowserCookie 是浏览器 Cookie 快照的适配器别名,仅用于测试和平台边界转换。
type BrowserCookie = cookierefresh.BrowserCookie
// WithCookieSnapshot 为平台请求上下文安装完整 Cookie 快照,并保留权威 Jar 的更新状态。
func WithCookieSnapshot(ctx context.Context, snapshot []BrowserCookie) (context.Context, *CookieSession) {
return mtop.WithCookieSnapshot(ctx, snapshot)
}
// WithFlatCookieSession 为历史扁平 Cookie 安装兼容会话,不伪造完整 Jar 属性。
func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) {
return mtop.WithFlatCookieSession(ctx, cookies)
}
// SnapshotFromMetadata 读取完整 Cookie 快照;解析失败或 metadata 不完整时返回 false。
func SnapshotFromMetadata(metadata string) ([]BrowserCookie, bool) {
return cookierefresh.SnapshotFromMetadataOK(metadata)
}
// HasStoredCookieCredential 判断凭证视图是否包含扁平 Cookie 或完整 Cookie 快照。
func HasStoredCookieCredential(detail *accountapp.CredentialDetail) bool {
if detail == nil {
return false
}
if detail.Value != "" {
return true
}
// complete 表示 metadata 是否包含可用于平台请求的完整快照。
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
// PersistCookieSessionLocked 持久化平台响应后的 Cookie 会话;调用方必须已持有凭证锁。
func PersistCookieSessionLocked(
ctx context.Context,
repository accountapp.CredentialRepository,
detail *accountapp.CredentialDetail,
session *CookieSession,
) (value string, valueChanged, handled bool, err error) {
if detail == nil || session == nil {
return "", false, false, nil
}
// value、snapshot、changed 保存平台会话当前 Cookie、完整快照及变更状态。
value, snapshot, changed := session.State()
if !changed {
if snapshot != nil {
return detail.Value, false, true, nil
}
return "", false, false, nil
}
// metadata 保存去除旧快照或合并新快照后的凭证元数据。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if repository == nil {
return value, value != detail.Value, true, errors.New("cookie 会话持久化 repository 未初始化")
}
// persistErr 保存凭证 Port 写回结果;明文 Cookie 不离开当前适配器调用边界。
persistErr := repository.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
if persistErr != nil {
return value, value != detail.Value, true, persistErr
}
return value, value != detail.Value, true, nil
}
+75
View File
@@ -0,0 +1,75 @@
package adapter
import (
"context"
"strings"
"testing"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/xianyu/cookierefresh"
)
// TestCookieSessionAdapterPersistsAuthoritativeSnapshot 验证平台 Cookie 会话快照经凭证 Port 写回并保留作用域。
func TestCookieSessionAdapterPersistsAuthoritativeSnapshot(t *testing.T) {
// store、cleanup 保存测试数据库及其资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是当前凭证会话测试共用的上下文。
ctx := context.Background()
// repository 是将 Cookie 写回 SQLite 的账号凭证适配器。
repository := NewAccountLoginRepository(store)
// detail、loadErr 保存平台调用所需的窄凭证视图及读取错误。
detail, loadErr := repository.LoadPlatformDetail(ctx, "cid")
if loadErr != nil {
t.Fatalf("读取凭证视图失败: %v", loadErr)
}
// sessionContext、session 保存本次平台流程的 Cookie 会话。
_, session := WithFlatCookieSession(ctx, detail.Value)
session.ReplaceSnapshot([]BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}})
// value、changed、handled、persistErr 保存会话写回结果及阶段错误。
value, changed, handled, persistErr := PersistCookieSessionLocked(ctx, repository, detail, session)
if persistErr != nil || !changed || !handled || value == "" {
t.Fatalf("快照写回异常: value=%q changed=%v handled=%v err=%v", value, changed, handled, persistErr)
}
// updated、updatedErr 保存写回后的平台凭证视图。
updated, updatedErr := repository.LoadPlatformDetail(ctx, detail.ID)
if updatedErr != nil {
t.Fatalf("读取写回凭证失败: %v", updatedErr)
}
// snapshot、complete 保存数据库中快照及完整性标记。
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON)
if !complete || len(snapshot) != 1 || snapshot[0].Value != "new" {
t.Fatalf("快照写回不完整: complete=%v snapshot=%+v", complete, snapshot)
}
}
// TestCookieSessionAdapterRejectsMissingRepository 验证凭证适配器缺失时不会伪装写回成功。
func TestCookieSessionAdapterRejectsMissingRepository(t *testing.T) {
// detail 是不含登录密码的最小平台凭证视图。
detail := &accountapp.CredentialDetail{ID: "cid", Value: "sid=old", MetadataJSON: "{}"}
// ctx、session 保存发生权威快照变化的当前平台会话。
ctx, session := WithFlatCookieSession(context.Background(), detail.Value)
session.ReplaceSnapshot([]BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}})
// _, changed、handled、persistErr 保存缺失 repository 时的结果。
_, changed, handled, persistErr := PersistCookieSessionLocked(ctx, nil, detail, session)
if !changed || !handled || persistErr == nil || !strings.Contains(persistErr.Error(), "repository 未初始化") {
t.Fatalf("缺失 repository 错误阶段异常: changed=%v handled=%v err=%v", changed, handled, persistErr)
}
}
// TestCookieSessionAdapterHasStoredCredential 验证扁平 Cookie 和完整快照均被识别为可用凭证。
func TestCookieSessionAdapterHasStoredCredential(t *testing.T) {
// flat 是只含扁平 Cookie 的历史平台凭证视图。
flat := &accountapp.CredentialDetail{Value: "sid=flat"}
if !HasStoredCookieCredential(flat) {
t.Fatal("扁平 Cookie 应被识别为已存储凭证")
}
// snapshotMetadata 是包含完整 Jar 的 metadata。
snapshotMetadata := cookierefresh.MetadataWithSnapshot(`{}`, []BrowserCookie{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}})
if !HasStoredCookieCredential(&accountapp.CredentialDetail{MetadataJSON: snapshotMetadata}) {
t.Fatal("完整 Cookie 快照应被识别为已存储凭证")
}
if HasStoredCookieCredential(nil) {
t.Fatal("空凭证视图不应被识别为已存储凭证")
}
}
+31
View File
@@ -0,0 +1,31 @@
package adapter
import (
"context"
"database/sql"
"errors"
"xianyu-go/internal/db"
)
// DatabaseHealth 将数据库连通性探测收口为 Server 健康检查所需的最小适配器。
type DatabaseHealth struct {
// database 保存待探测的数据库连接;连接生命周期仍由数据库装配方负责关闭。
database *sql.DB
}
// NewDatabaseHealth 创建数据库健康检查适配器,缺少 Store 时保留可诊断的空依赖实例。
func NewDatabaseHealth(store *db.Store) *DatabaseHealth {
if store == nil {
return &DatabaseHealth{}
}
return &DatabaseHealth{database: store.DB}
}
// Ping 在调用方 Context 限制内探测数据库连接,避免 HTTP 层直接访问 SQL 连接。
func (health *DatabaseHealth) Ping(ctx context.Context) error {
if health == nil || health.database == nil {
return errors.New("数据库健康检查未初始化")
}
return health.database.PingContext(ctx)
}
+42
View File
@@ -0,0 +1,42 @@
package adapter
import (
"context"
"testing"
"xianyu-go/internal/db"
)
// TestDatabaseHealthRejectsMissingDependency 验证健康检查缺少数据库时不会伪装成功。
func TestDatabaseHealthRejectsMissingDependency(t *testing.T) {
// health 保存缺少 Store 的数据库健康检查适配器。
health := NewDatabaseHealth(nil)
// err 保存缺少数据库依赖时的探测错误。
if err := health.Ping(context.Background()); err == nil {
t.Fatal("缺少数据库时健康检查不应成功")
}
}
// TestDatabaseHealthPingsDatabase 验证健康检查适配器能够在 Context 内探测 SQLite 连接。
func TestDatabaseHealthPingsDatabase(t *testing.T) {
// database、dialect 和 openErr 保存临时 SQLite 连接及其方言。
database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/health.db")
if openErr != nil {
t.Fatalf("打开测试数据库失败: %v", openErr)
}
defer database.Close()
// health 保存绑定 SQLite 连接的健康检查适配器。
health := NewDatabaseHealth(db.NewStore(database, dialect))
// err 保存数据库连接仍可用时的探测错误。
if err := health.Ping(context.Background()); err != nil {
t.Fatalf("数据库健康检查失败: %v", err)
}
// closeErr 保存关闭数据库后的探测错误,验证故障状态会被上报。
if closeErr := database.Close(); closeErr != nil {
t.Fatalf("关闭测试数据库失败: %v", closeErr)
}
// err 保存数据库已关闭后的探测错误。
if err := health.Ping(context.Background()); err == nil {
t.Fatal("关闭数据库后健康检查不应成功")
}
}
@@ -0,0 +1,133 @@
package adapter
import (
"context"
"errors"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
"xianyu-go/internal/db"
)
// DefaultReplyRepository 将默认回复数据库仓储适配为应用层消费者定义的 Port。
type DefaultReplyRepository struct {
// store 保存数据库聚合入口;敏感账号字段只由 Cookies 的非敏感归属方法访问。
store *db.Store
}
// NewDefaultReplyRepository 创建默认回复数据库适配器。
func NewDefaultReplyRepository(store *db.Store) *DefaultReplyRepository {
// repository 保存后续用例调用所需的数据库聚合入口。
repository := &DefaultReplyRepository{store: store}
return repository
}
// CheckOwnership 查询账号所有者,并把数据库缺失错误转换为应用错误。
func (r *DefaultReplyRepository) CheckOwnership(ctx context.Context, userID int64, cookieID string) (defaultreplyapp.AccountOwnership, error) {
// err 表示适配器依赖缺失或账号所有权查询失败的原因。
if err := r.validate(); err != nil {
return defaultreplyapp.AccountOwnership{}, err
}
// owned 表示账号是否直接属于当前用户;查询不读取账号凭证。
owned, err := r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
if err != nil {
return defaultreplyapp.AccountOwnership{}, err
}
if owned {
return defaultreplyapp.AccountOwnership{OwnerID: userID}, nil
}
// ownerID 保存账号的非敏感所有者标识,用于区分不存在和跨用户访问。
ownerID, err := r.store.Cookies.GetOwnerID(ctx, cookieID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return defaultreplyapp.AccountOwnership{}, defaultreplyapp.ErrAccountNotFound
}
return defaultreplyapp.AccountOwnership{}, err
}
return defaultreplyapp.AccountOwnership{OwnerID: ownerID}, nil
}
// Get 读取单个账号默认回复,并隐藏数据库模型与 ErrNotFound 语义。
func (r *DefaultReplyRepository) Get(ctx context.Context, cookieID string) (defaultreplyapp.Reply, error) {
// err 表示适配器依赖缺失或默认回复读取失败的原因。
if err := r.validate(); err != nil {
return defaultreplyapp.Reply{}, err
}
// record、err 保存数据库默认回复记录及读取错误。
record, err := r.store.DefaultReps.Get(ctx, cookieID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return defaultreplyapp.Reply{}, defaultreplyapp.ErrConfigNotFound
}
return defaultreplyapp.Reply{}, err
}
return defaultreplyapp.Reply{
Enabled: record.Enabled, ReplyContent: record.ReplyContent,
ReplyImageURL: record.ReplyImageURL, ReplyOnce: record.ReplyOnce,
}, nil
}
// Upsert 将应用默认回复模型转换为数据库模型并保存。
func (r *DefaultReplyRepository) Upsert(ctx context.Context, cookieID string, reply defaultreplyapp.Reply) error {
// err 表示适配器依赖缺失或默认回复写入失败的原因。
if err := r.validate(); err != nil {
return err
}
return r.store.DefaultReps.Upsert(ctx, cookieID, db.DefaultReply{
Enabled: reply.Enabled, ReplyContent: reply.ReplyContent,
ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce,
})
}
// ListForUser 查询用户默认回复摘要并转换为应用模型。
func (r *DefaultReplyRepository) ListForUser(ctx context.Context, userID int64) ([]defaultreplyapp.Summary, error) {
// err 表示适配器依赖缺失或默认回复列表查询失败的原因。
if err := r.validate(); err != nil {
return nil, err
}
// records、err 保存数据库摘要列表及查询错误。
records, err := r.store.DefaultReps.ListForUser(ctx, userID)
if err != nil {
return nil, err
}
// result 保存不暴露数据库模型的应用层默认回复摘要。
result := make([]defaultreplyapp.Summary, 0, len(records))
// record 表示当前待转换的数据库默认回复摘要。
for _, record := range records {
result = append(result, defaultreplyapp.Summary{
CookieID: record.CookieID,
Reply: defaultreplyapp.Reply{
Enabled: record.Enabled, ReplyContent: record.ReplyContent,
ReplyImageURL: record.ReplyImageURL, ReplyOnce: record.ReplyOnce,
},
})
}
return result, nil
}
// Delete 删除指定账号的默认回复配置。
func (r *DefaultReplyRepository) Delete(ctx context.Context, cookieID string) error {
// err 表示适配器依赖缺失或默认回复删除失败的原因。
if err := r.validate(); err != nil {
return err
}
return r.store.DefaultReps.Delete(ctx, cookieID)
}
// ClearRecords 删除指定账号的默认回复投递记录。
func (r *DefaultReplyRepository) ClearRecords(ctx context.Context, cookieID string) error {
// err 表示适配器依赖缺失或投递记录清理失败的原因。
if err := r.validate(); err != nil {
return err
}
return r.store.DefaultReps.ClearRecords(ctx, cookieID)
}
// validate 检查数据库聚合入口及默认回复子仓储是否已装配。
func (r *DefaultReplyRepository) validate() error {
if r == nil || r.store == nil || r.store.DefaultReps == nil || r.store.Cookies == nil {
return errors.New("默认回复数据库适配器未初始化")
}
return nil
}
var _ defaultreplyapp.Repository = (*DefaultReplyRepository)(nil)
@@ -0,0 +1,117 @@
package adapter
import (
"context"
"errors"
"testing"
defaultreplyapp "xianyu-go/internal/application/defaultreply"
)
// TestDefaultReplyRepositoryCRUDMapping 验证默认回复 CRUD 和应用模型之间的字段映射。
func TestDefaultReplyRepositoryCRUDMapping(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的默认回复数据库适配器。
repository := NewDefaultReplyRepository(store)
// ctx 是本测试所有数据库操作使用的非取消上下文。
ctx := context.Background()
// owner 是测试模板中创建的默认管理员用户。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// ownership、ownershipErr 保存账号所有权 Port 的返回结果。
ownership, ownershipErr := repository.CheckOwnership(ctx, owner.ID, "cid")
if ownershipErr != nil || ownership.OwnerID != owner.ID {
t.Fatalf("账号归属映射异常 ownership=%+v err=%v", ownership, ownershipErr)
}
// input 是覆盖全部默认回复字段的应用模型。
input := defaultreplyapp.Reply{Enabled: true, ReplyContent: "你好", ReplyImageURL: "https://example.invalid/reply.png", ReplyOnce: true}
// upsertErr 表示保存默认回复的数据库错误。
if upsertErr := repository.Upsert(ctx, "cid", input); upsertErr != nil {
t.Fatal(upsertErr)
}
// got、getErr 保存适配器转换后的默认回复模型及查询错误。
got, getErr := repository.Get(ctx, "cid")
if getErr != nil || got != input {
t.Fatalf("默认回复字段映射异常 got=%+v want=%+v err=%v", got, input, getErr)
}
// listed、listErr 保存按用户隔离的默认回复摘要列表。
listed, listErr := repository.ListForUser(ctx, owner.ID)
if listErr != nil || len(listed) != 1 || listed[0].CookieID != "cid" || listed[0].Reply != input {
t.Fatalf("默认回复列表映射异常 listed=%+v err=%v", listed, listErr)
}
// updated 是第二次写入的应用模型,用于验证覆盖语义。
updated := defaultreplyapp.Reply{Enabled: false, ReplyContent: "更新后"}
// updateErr 表示覆盖默认回复的数据库错误。
if updateErr := repository.Upsert(ctx, "cid", updated); updateErr != nil {
t.Fatal(updateErr)
}
// afterUpdate、afterUpdateErr 保存覆盖后的默认回复模型及查询错误。
afterUpdate, afterUpdateErr := repository.Get(ctx, "cid")
if afterUpdateErr != nil || afterUpdate != updated {
t.Fatalf("默认回复覆盖异常 got=%+v err=%v", afterUpdate, afterUpdateErr)
}
// clearErr 表示清理默认回复投递记录的数据库错误。
if clearErr := repository.ClearRecords(ctx, "cid"); clearErr != nil {
t.Fatal(clearErr)
}
// deleteErr 表示删除默认回复的数据库错误。
if deleteErr := repository.Delete(ctx, "cid"); deleteErr != nil {
t.Fatal(deleteErr)
}
// missingErr 保存删除后读取配置的应用层缺失错误。
if _, missingErr := repository.Get(ctx, "cid"); !errors.Is(missingErr, defaultreplyapp.ErrConfigNotFound) {
t.Fatalf("删除后应映射为配置缺失,err=%v", missingErr)
}
}
// TestDefaultReplyRepositoryOwnershipErrors 验证不存在账号和跨用户账号的非敏感归属语义。
func TestDefaultReplyRepositoryOwnershipErrors(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定 SQLite 存储的默认回复数据库适配器。
repository := NewDefaultReplyRepository(store)
// ctx 是本测试使用的非取消上下文。
ctx := context.Background()
// missingErr 保存不存在账号的归属查询错误。
_, missingErr := repository.CheckOwnership(ctx, 1, "missing-account")
if !errors.Is(missingErr, defaultreplyapp.ErrAccountNotFound) {
t.Fatalf("不存在账号应返回应用缺失错误,err=%v", missingErr)
}
// otherErr 保存跨用户账号的归属查询错误;模板账号 cid 属于管理员。
other, otherErr := repository.CheckOwnership(ctx, 999, "cid")
if otherErr != nil || other.OwnerID != 1 {
t.Fatalf("跨用户归属应返回真实所有者而非敏感数据 owner=%+v err=%v", other, otherErr)
}
}
// TestDefaultReplyRepositoryPropagatesInfrastructureErrors 验证数据库不可用时不伪装为业务缺失。
func TestDefaultReplyRepositoryPropagatesInfrastructureErrors(t *testing.T) {
// store 是随后主动关闭数据库连接的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定已关闭数据库的默认回复适配器。
repository := NewDefaultReplyRepository(store)
// closeErr 表示主动关闭测试数据库连接时的资源释放错误。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// err 保存数据库关闭后执行默认回复查询的底层错误。
if _, err := repository.Get(context.Background(), "cid"); err == nil || errors.Is(err, defaultreplyapp.ErrConfigNotFound) {
t.Fatalf("数据库故障应透传而非映射为配置缺失,err=%v", err)
}
// ownershipErr 保存数据库关闭后执行归属查询的底层错误。
if _, ownershipErr := repository.CheckOwnership(context.Background(), 1, "cid"); ownershipErr == nil {
t.Fatal("数据库故障时归属查询应返回错误")
}
// invalidErr 保存空适配器的装配错误。
if _, invalidErr := NewDefaultReplyRepository(nil).ListForUser(context.Background(), 1); invalidErr == nil {
t.Fatal("缺少 Store 时应返回适配器装配错误")
}
}
var _ defaultreplyapp.Repository = (*DefaultReplyRepository)(nil)
+97
View File
@@ -0,0 +1,97 @@
package adapter
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
// ItemBatchPreviewPort 将批量预检所需的非敏感归属与本地路径校验适配到基础设施。
type ItemBatchPreviewPort struct {
// store 提供账号和卡券归属查询能力。
store *db.Store
}
// NewItemBatchPreviewPort 创建批量预检基础设施 Port。
func NewItemBatchPreviewPort(store *db.Store) *ItemBatchPreviewPort {
return &ItemBatchPreviewPort{store: store}
}
// CookieOwned 判断账号是否属于用户,不读取或解密 Cookie 内容。
func (port *ItemBatchPreviewPort) CookieOwned(ctx context.Context, userID int64, cookieID string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := port.validate(); err != nil {
return false, err
}
return port.store.Cookies.ExistsOwned(ctx, userID, strings.TrimSpace(cookieID))
}
// CardOwned 判断卡券组是否属于用户,不向应用层暴露卡券库存内容。
func (port *ItemBatchPreviewPort) CardOwned(ctx context.Context, userID, cardID int64) (bool, error) {
// err 表示适配器依赖校验错误。
if err := port.validate(); err != nil {
return false, err
}
return port.store.Cards.ExistsOwned(ctx, cardID, userID)
}
// ValidateImageReference 校验本地图片路径位于指定上传目录内且对应普通文件。
func (port *ItemBatchPreviewPort) ValidateImageReference(uploadDir, reference string) error {
_ = port
if isPreviewHTTPURL(reference) {
return nil
}
// relative 和 err 表示清理后的相对路径及安全校验错误。
relative, err := safePreviewPath(reference)
if err != nil {
return err
}
// path 表示上传根目录下的目标文件路径。
path := filepath.Join(uploadDir, relative)
// info 和 err 表示文件属性及读取错误。
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return fmt.Errorf("图片文件不存在: %s", reference)
}
return nil
}
// validate 检查账号和卡券子仓储是否已装配。
func (port *ItemBatchPreviewPort) validate() error {
if port == nil || port.store == nil || port.store.Cookies == nil || port.store.Cards == nil {
return errors.New("批量预检数据库适配器未初始化")
}
return nil
}
// isPreviewHTTPURL 判断图片引用是否为允许的远程 HTTP 地址。
func isPreviewHTTPURL(reference string) bool {
// value 保存标准化后的远程地址文本。
value := strings.ToLower(strings.TrimSpace(reference))
return strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://")
}
// safePreviewPath 清理本地图片路径并拒绝绝对路径和目录穿越。
func safePreviewPath(raw string) (string, error) {
// value 保存统一路径分隔符后的原始路径。
value := strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/"))
if value == "" || strings.HasPrefix(value, "/") {
return "", fmt.Errorf("图片路径不安全: %s", value)
}
// clean 保存清理后的相对路径。
clean := filepath.Clean(value)
if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) {
return "", fmt.Errorf("图片路径不安全: %s", value)
}
return clean, nil
}
// 确保适配器实现批量预检的所有基础设施 Port。
var _ itemapp.BatchPreviewOwnershipPort = (*ItemBatchPreviewPort)(nil)
var _ itemapp.BatchPreviewImagePort = (*ItemBatchPreviewPort)(nil)
@@ -0,0 +1,60 @@
package adapter
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// TestItemBatchPreviewPortRejectsMissingStore 验证归属查询在未装配数据库时快速失败。
func TestItemBatchPreviewPortRejectsMissingStore(t *testing.T) {
// port 是未装配数据库的批量预检适配器。
port := NewItemBatchPreviewPort(nil)
// err 表示账号归属查询错误。
if _, err := port.CookieOwned(context.Background(), 1, "acc1"); err == nil {
t.Error("CookieOwned() expected missing store error")
}
// err 表示卡券归属查询错误。
if _, err := port.CardOwned(context.Background(), 1, 1); err == nil {
t.Error("CardOwned() expected missing store error")
}
}
// TestItemBatchPreviewPortValidatesImageReferences 验证本地图片路径安全规则和普通文件检查。
func TestItemBatchPreviewPortValidatesImageReferences(t *testing.T) {
// port 是只使用路径校验能力的批量预检适配器。
port := NewItemBatchPreviewPort(nil)
// root 是测试上传目录。
root := t.TempDir()
// imagePath 是测试图片的绝对路径。
imagePath := filepath.Join(root, "img", "a.png")
// err 表示测试图片目录创建错误。
if err := os.MkdirAll(filepath.Dir(imagePath), 0o750); err != nil {
t.Fatalf("MkdirAll() error = %v", err)
}
// err 表示测试图片写入错误。
if err := os.WriteFile(imagePath, []byte("png"), 0o640); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
// err 表示有效本地图片校验错误。
if err := port.ValidateImageReference(root, "img/a.png"); err != nil {
t.Fatalf("valid image reference error = %v", err)
}
// err 表示远程图片校验错误。
if err := port.ValidateImageReference(root, "https://example.com/a.png"); err != nil {
t.Fatalf("remote image reference error = %v", err)
}
// reference 表示当前待拒绝的图片引用。
for _, reference := range []string{"../a.png", "/tmp/a.png", "missing.png"} {
// err 表示不安全或不存在图片的校验结果。
if err := port.ValidateImageReference(root, reference); err == nil {
t.Errorf("ValidateImageReference(%q) expected error", reference)
}
}
// err 表示路径穿越校验错误。
if err := port.ValidateImageReference(root, "../a.png"); !strings.Contains(err.Error(), "图片路径不安全") {
t.Fatalf("path traversal error = %v", err)
}
}
+382
View File
@@ -0,0 +1,382 @@
package adapter
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// ItemBatchPublishPort 将批量发布的 MTOP 调用、凭证会话和远端检查点适配为应用端口。
type ItemBatchPublishPort struct {
// store 提供批次检查点、平台凭证和 Cookie 会话持久化能力。
store *db.Store
// client 返回当前批量发布使用的平台客户端,允许测试替换实现。
client func() mtop.Client
// logger 记录不含凭证明文的会话提交错误。
logger *slog.Logger
// updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。
updateRunningCookie func(context.Context, string, string)
// recoverExpiredSession 在平台报告会话失效时触发账号恢复协调。
recoverExpiredSession func(context.Context, string, error)
// readImage 从受控上传目录读取并校验本地图片。
readImage ReadPublishImageFile
// downloadImage 下载并校验批量发布使用的远程图片。
downloadImage DownloadPublishImageURL
}
// NewItemBatchPublishPort 构造批量发布远端适配器并注入图片安全回调。
func NewItemBatchPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error), readImage ReadPublishImageFile, downloadImage DownloadPublishImageURL) *ItemBatchPublishPort {
// resolvedLogger 保存可用于记录适配器错误的日志器。
resolvedLogger := logger
if resolvedLogger == nil {
resolvedLogger = slog.Default()
}
return &ItemBatchPublishPort{store: store, client: client, logger: resolvedLogger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession, readImage: readImage, downloadImage: downloadImage}
}
// PublishRemoteRow 执行单行商品远端发布并保存远端结果检查点,不写入本地商品或自动化规则。
func (p *ItemBatchPublishPort) PublishRemoteRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) (itemapp.BatchPublishOutcome, error) {
// validateErr 保存适配器依赖校验错误。
if validateErr := p.validate(); validateErr != nil {
return itemapp.BatchPublishOutcome{}, validateErr
}
// batch、batchErr 保存按用户隔离后的批次配置。
batch, batchErr := p.store.PublishBatches.Get(ctx, userID, row.BatchID)
if batchErr != nil || batch == nil {
return itemapp.BatchPublishOutcome{}, errors.New("批量任务不存在")
}
// savedResult 保存已完成远端发布的断点,重试时禁止再次调用平台。
if strings.TrimSpace(row.ItemID) != "" {
return itemapp.BatchPublishOutcome{Result: batchPublishResultFromRow(row)}, nil
}
// imageDependencyErr 保存新建远端商品所需的图片读取依赖校验错误;已保存检查点的重试已在此前返回。
if imageDependencyErr := p.validateImageDependencies(); imageDependencyErr != nil {
return itemapp.BatchPublishOutcome{}, imageDependencyErr
}
// location、locationErr 保存批次发货地配置及解析错误。
location, locationErr := batchPublishLocation(batch.LocationJSON)
if locationErr != nil {
return itemapp.BatchPublishOutcome{}, locationErr
}
// priceCents、priceErr 保存商品售价的分值表示。
priceCents, priceErr := parseBatchMoneyCents(row.Price)
if priceErr != nil || priceCents <= 0 {
return itemapp.BatchPublishOutcome{}, errors.New("商品价格必须大于 0")
}
// originalPriceCents、postageCents 保存原价和邮费的分值表示。
originalPriceCents, _ := parseBatchMoneyCents(row.OriginalPrice)
// postageCents 保存邮费的分值表示。
postageCents, _ := parseBatchMoneyCents(row.Postage)
// preferredCategory 保存批次配置的可选发布类目。
preferredCategory, categoryErr := batchPublishCategory(row.CategoryJSON)
if categoryErr != nil {
return itemapp.BatchPublishOutcome{}, categoryErr
}
// images、imageErr 保存平台发布需要的本地或远程图片内容。
images, imageErr := LoadBatchPublishImages(ctx, batch.UploadDir, row.ImagesJSON, p.readImage, p.downloadImage)
if imageErr != nil {
return itemapp.BatchPublishOutcome{}, imageErr
}
// markCtx、markCancel 限制远端开始检查点写入时间,避免租约失效时无限等待。
markCtx, markCancel := batchPublishStatusContext(ctx)
// remoteStarted、markErr 保存远端开始检查点的写入结果。
remoteStarted, markErr := p.store.PublishBatches.MarkClaimedRemoteStarted(markCtx, row.ID, workerToken)
markCancel()
if markErr != nil || !remoteStarted {
return itemapp.BatchPublishOutcome{}, fmt.Errorf("保存远端发布前检查点失败: %w", firstBatchError(markErr, itemapp.ErrBatchLeaseLost))
}
// unlock、latest、loadErr 保存凭证快照读取及其串行化锁释放结果。
unlock := p.store.LockAccountCredentials(row.CookieID)
// latest、loadErr 保存加锁读取的平台凭证视图及错误。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, row.CookieID)
if loadErr != nil || latest.UserID != userID || !hasStoredCredential(latest) {
unlock()
return itemapp.BatchPublishOutcome{}, errors.New("账号凭证已变化,请重试")
}
// initialValue、initialMetadata 用于远端返回后复核期间的凭证一致性。
initialValue, initialMetadata := latest.Value, latest.MetadataJSON
// requestCtx、cancel 控制单行远端发布的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
// mtopCtx、cookieSession 挂载本次调用使用的 Cookie 会话。
mtopCtx, cookieSession := withCookieSnapshot(requestCtx, latest)
// unlock 在远端 I/O 前释放,避免凭证锁覆盖慢速平台请求。
unlock()
// result、callErr 保存平台返回结果及调用错误。
result, callErr := p.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{
Title: row.Title, Description: firstBatchNonEmpty(row.Description, row.Title), PriceCents: priceCents,
OriginalPriceCents: originalPriceCents, Quantity: row.Quantity, PostageMode: row.PostageMode,
PostageCents: postageCents, Virtual: true, Location: location, PreferredCategory: preferredCategory, Images: images,
})
cancel()
// runtimeCookie、persistErr 保存会话写回后的运行时 Cookie 和错误。
runtimeCookie, persistErr := p.persistBatchSession(ctx, userID, row.CookieID, initialValue, initialMetadata, cookieSession, result, callErr)
if runtimeCookie != "" && p.updateRunningCookie != nil {
p.updateRunningCookie(ctx, row.CookieID, runtimeCookie)
}
if persistErr != nil && callErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
}
if callErr != nil {
p.recoverExpired(ctx, row.CookieID, callErr)
if ctx.Err() != nil {
return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("取消时远端发布结果未知: %w", ctx.Err())}
}
// publishErr 保存库存权限等可直接展示的确定性平台错误。
var publishErr *mtop.PublishError
if errors.As(callErr, &publishErr) && publishErr.Code == mtop.PublishErrorStockPermissionMissing {
return itemapp.BatchPublishOutcome{}, errors.New("该账号没有库存发布权限,无法按库存数量发布商品")
}
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
return itemapp.BatchPublishOutcome{}, callErr
}
return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("远端发布调用失败且结果未知: %w", callErr)}
}
if result == nil {
return itemapp.BatchPublishOutcome{}, errors.New("发布商品接口未返回结果")
}
// rawJSON 保存远端原始结果,供重试恢复和本地详情持久化使用。
rawJSON, _ := json.Marshal(result.RawData)
// saveCtx、saveCancel 限制远端结果检查点写入时间。
saveCtx, saveCancel := batchPublishStatusContext(ctx)
// saved、saveErr 保存远端结果检查点的写入结果。
saved, saveErr := p.store.PublishBatches.SaveClaimedRemoteResult(saveCtx, row.ID, workerToken, result.ItemID, result.ItemURL, string(rawJSON))
saveCancel()
if saveErr != nil || !saved {
return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("保存远端发布结果失败: %w", firstBatchError(saveErr, itemapp.ErrBatchLeaseLost))}
}
// outcome 保存平台结果和已完成远端调用后的 Cookie 后置错误。
outcome := itemapp.BatchPublishOutcome{Result: batchPublishResultFromMTOP(result)}
if persistErr != nil {
outcome.ResponseCookieErr = persistErr
}
return outcome, nil
}
// persistBatchSession 在远端调用结束后复核凭证并写回 Cookie 会话变化。
func (p *ItemBatchPublishPort) persistBatchSession(ctx context.Context, userID int64, cookieID, initialValue, initialMetadata string, session *mtop.CookieSession, result *mtop.PublishItemResult, callErr error) (string, error) {
// unlock 保护远端调用完成后的凭证复核和持久化。
unlock := p.store.LockAccountCredentials(cookieID)
defer unlock()
// latest、loadErr 保存远端调用完成后的最新平台凭证视图。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if loadErr != nil || latest.UserID != userID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata {
return "", errors.New("账号凭证已变化,请重试")
}
// value、valueChanged、handled、persistErr 保存会话持久化状态。
value, valueChanged, handled, persistErr := persistBatchCookieSession(ctx, p.store, latest, session)
if persistErr != nil {
if p.logger != nil {
p.logger.Error("保存批量发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
}
return "", persistErr
}
if handled && valueChanged {
return value, nil
}
if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value {
// saveErr 保存平台返回平面 Cookie 的写回错误。
if saveErr := p.store.Cookies.UpdateValueOwned(ctx, cookieID, result.UpdatedCookies, userID); saveErr != nil {
return "", saveErr
}
return result.UpdatedCookies, nil
}
return "", nil
}
// persistBatchCookieSession 保存完整 Cookie Jar 或兼容的平面 Cookie 会话。
func persistBatchCookieSession(ctx context.Context, store *db.Store, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) {
if session == nil {
return "", false, false, nil
}
// value、snapshot、changed 保存平台会话当前状态。
value, snapshot, changed := session.State()
if !changed {
return detail.Value, false, snapshot != nil, nil
}
// metadata 保存移除旧快照后待写入的新 metadata。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
// persistErr 保存 Cookie 会话的加密持久化结果。
persistErr := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
return value, value != detail.Value, true, persistErr
}
// validate 检查批量远端适配器所需的数据库、图片和平台依赖。
func (p *ItemBatchPublishPort) validate() error {
if p == nil || p.store == nil || p.store.Cookies == nil || p.store.PublishBatches == nil {
return errors.New("批量发布远端适配器未初始化")
}
return nil
}
// validateImageDependencies 检查新建远端商品时必需的图片安全回调。
func (p *ItemBatchPublishPort) validateImageDependencies() error {
if p.readImage == nil || p.downloadImage == nil {
return errors.New("批量发布图片读取端口未初始化")
}
return nil
}
// mtopClient 返回当前平台客户端,并在测试构造缺失时提供默认实现。
func (p *ItemBatchPublishPort) mtopClient() mtop.Client {
if p != nil && p.client != nil {
// resolvedClient 保存回调返回的平台客户端。
if resolvedClient := p.client(); resolvedClient != nil {
return resolvedClient
}
}
return mtop.NewClient()
}
// recoverExpired 在平台会话失效时通知账号恢复协调器。
func (p *ItemBatchPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) {
if p != nil && p.recoverExpiredSession != nil && err != nil {
p.recoverExpiredSession(ctx, cookieID, err)
}
}
// batchPublishResultFromMTOP 将平台结果转换为不泄露平台类型的应用结果。
func batchPublishResultFromMTOP(result *mtop.PublishItemResult) *itemapp.BatchPublishResult {
if result == nil {
return nil
}
return &itemapp.BatchPublishResult{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}
}
// batchPublishResultFromRow 将已有远端检查点转换为应用结果,避免重试重复调用平台。
func batchPublishResultFromRow(row itemapp.BatchRow) *itemapp.BatchPublishResult {
// rawData 保存已有远端结果的结构化 JSON。
rawData := map[string]any{}
if strings.TrimSpace(row.RawJSON) != "" {
_ = json.Unmarshal([]byte(row.RawJSON), &rawData)
}
return &itemapp.BatchPublishResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity, RawData: rawData}
}
// batchPublishLocation 解析批次级别的发货地配置。
func batchPublishLocation(raw string) (*mtop.PublishLocation, error) {
if strings.TrimSpace(raw) == "" {
raw = "{}"
}
// location 保存批次发货地配置。
var location mtop.PublishLocation
// decodeErr 保存发货地 JSON 解析错误。
if decodeErr := json.Unmarshal([]byte(raw), &location); decodeErr != nil {
return nil, errors.New("批量任务发货地配置损坏,请重新创建任务")
}
if strings.TrimSpace(location.DivisionID) == "" {
return nil, nil
}
return &location, nil
}
// batchPublishCategory 解析批次默认类目并校验平台必需字段。
func batchPublishCategory(raw string) (*mtop.PublishCategory, error) {
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" {
return nil, nil
}
// category 保存批次默认类目配置。
var category mtop.PublishCategory
// decodeErr 保存类目 JSON 解析错误。
if decodeErr := json.Unmarshal([]byte(raw), &category); decodeErr != nil {
return nil, errors.New("默认类目配置损坏,请重新创建批量任务")
}
if strings.TrimSpace(category.CatID) == "" && strings.TrimSpace(category.CatName) == "" && strings.TrimSpace(category.ChannelCatID) == "" && strings.TrimSpace(category.TBCatID) == "" {
return nil, nil
}
if strings.TrimSpace(category.CatID) == "" || strings.TrimSpace(category.CatName) == "" || strings.TrimSpace(category.ChannelCatID) == "" {
return nil, errors.New("默认类目信息不完整,请重新创建批量任务")
}
return &category, nil
}
// parseBatchMoneyCents 将用户金额文本转换为平台使用的分值。
func parseBatchMoneyCents(raw string) (int64, error) {
raw = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(raw, "¥"), "¥"))
if raw == "" {
return 0, nil
}
// sign、unsigned 保存金额符号和去除符号后的文本。
sign := int64(1)
// unsigned 保存去除金额符号后的文本。
unsigned := raw
if strings.HasPrefix(unsigned, "-") {
sign, unsigned = -1, strings.TrimPrefix(unsigned, "-")
} else {
unsigned = strings.TrimPrefix(unsigned, "+")
}
// parts 保存整数和小数部分。
parts := strings.Split(unsigned, ".")
if len(parts) > 2 {
return 0, errors.New("金额格式错误")
}
// yuan、err 保存元金额及解析错误。
yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
if err != nil {
return 0, err
}
// cents 保存补齐两位小数后的分金额。
cents := int64(0)
if len(parts) == 2 {
// fraction 保存金额的小数部分。
fraction := strings.TrimSpace(parts[1])
if len(fraction) > 2 {
return 0, errors.New("金额最多支持两位小数")
}
for len(fraction) < 2 {
fraction += "0"
}
cents, err = strconv.ParseInt(fraction, 10, 64)
if err != nil {
return 0, err
}
}
return sign * (yuan*100 + cents), nil
}
// batchPublishStatusContext 为远端检查点写入提供独立的短超时。
func batchPublishStatusContext(parent context.Context) (context.Context, context.CancelFunc) {
if parent != nil && parent.Err() == nil {
return context.WithTimeout(parent, 5*time.Second)
}
return context.WithTimeout(context.Background(), 5*time.Second)
}
// firstBatchError 返回第一个有效错误,确保租约错误不会覆盖数据库错误。
func firstBatchError(err, fallback error) error {
if err != nil {
return err
}
return fallback
}
// firstBatchNonEmpty 返回候选文本中第一个非空白值。
func firstBatchNonEmpty(values ...string) string {
// value 表示当前候选文本。
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
// 确保批量远端适配器实现应用层定义的端口。
var _ itemapp.BatchPublishPort = (*ItemBatchPublishPort)(nil)
// IsSessionExpiredError 判断批量发布错误是否要求终止剩余明细并进入账号恢复。
func IsSessionExpiredError(err error) bool {
return mtop.IsSessionExpiredErr(err)
}
+116
View File
@@ -0,0 +1,116 @@
package adapter
import (
"context"
"testing"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// batchPublishClientStub 是批量远端发布测试使用的平台客户端替身。
type batchPublishClientStub struct {
// mtop.Client 提供未涉及本测试的方法默认实现。
mtop.Client
// publish 保存批量发布请求的可控行为。
publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error)
}
// PublishItem 调用测试注入的批量发布行为。
func (c batchPublishClientStub) PublishItem(ctx context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return c.publish(ctx, cookies, request)
}
// TestItemBatchPublishPortPersistsRemoteCheckpoint 验证批量远端端口完成租约检查点和 Cookie 写回。
func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// admin、adminErr 保存批次所属用户及读取错误。
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
if adminErr != nil {
t.Fatalf("读取测试用户失败: %v", adminErr)
}
// batch 保存待发布的批次配置。
batch := &db.ItemPublishBatch{ID: "batch-remote-port", UserID: admin.ID, DefaultCookieID: "cid", UploadDir: t.TempDir(), LocationJSON: `{"division_id":"330100"}`, Status: "pending"}
// rows 保存待发布的单条明细。
rows := []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "cid", Title: "批量商品", Description: "批量描述", Price: "12.50", Quantity: 2, PostageMode: "free", ImagesJSON: `["a.png"]`, CategoryJSON: `{"cat_id":"1","cat_name":"类目","channel_cat_id":"2"}`, Status: "pending"}}
// createErr 保存批次写入错误。
if createErr := store.PublishBatches.Create(ctx, batch, rows); createErr != nil {
t.Fatalf("创建测试批次失败: %v", createErr)
}
// lease 保存本次 worker 的有效租约时间。
lease := time.Now().UTC().Add(time.Minute).Unix()
// claimed、claimErr 保存批次租约抢占结果。
claimed, claimErr := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-remote", lease)
if claimErr != nil || !claimed {
t.Fatalf("抢占批次失败: claimed=%v err=%v", claimed, claimErr)
}
// storedRows、rowsErr 保存抢占后的明细行。
storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID)
if rowsErr != nil || len(storedRows) != 1 {
t.Fatalf("读取测试明细失败: rows=%+v err=%v", storedRows, rowsErr)
}
// rowClaimed、rowClaimErr 保存明细租约抢占结果。
rowClaimed, rowClaimErr := store.PublishBatches.ClaimRow(ctx, storedRows[0].ID, "worker-remote")
if rowClaimErr != nil || !rowClaimed {
t.Fatalf("抢占明细失败: claimed=%v err=%v", rowClaimed, rowClaimErr)
}
// publishCalls 记录平台调用次数,用于确认远端检查点重试不会再次创建商品。
publishCalls := 0
// client 是返回成功商品和新 Cookie 的平台替身。
client := batchPublishClientStub{publish: func(_ context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
publishCalls++
if cookies == "" || request.PriceCents != 1250 || request.Quantity != 2 || len(request.Images) != 1 {
t.Fatalf("平台请求字段异常: cookies=%q price=%d quantity=%d images=%d", cookies, request.PriceCents, request.Quantity, len(request.Images))
}
return &mtop.PublishItemResult{ItemID: "remote-item", ItemURL: "https://example.test/item/remote-item", Title: "批量商品", PriceText: "12.50", Quantity: 2, UpdatedCookies: "unb=2; _m_h5_tk=next"}, nil
}}
// port 是绑定测试数据库、平台替身和图片回调的批量远端适配器。
port := NewItemBatchPublishPort(store, func() mtop.Client { return client }, nil, nil, nil,
func(_ string, ref string) ([]byte, string, string, error) {
return []byte("image"), "image/png", ref, nil
},
func(context.Context, string) ([]byte, string, error) { return nil, "", nil })
// outcome、publishErr 保存远端端口结果及错误。
outcome, publishErr := port.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(storedRows[0]), "worker-remote")
if publishErr != nil || outcome.Result == nil || outcome.Result.ItemID != "remote-item" {
t.Fatalf("远端端口结果异常: outcome=%+v err=%v", outcome, publishErr)
}
// savedRows、savedErr 保存远端检查点和明细状态。
savedRows, savedErr := store.PublishBatches.Rows(ctx, batch.ID)
if savedErr != nil || len(savedRows) != 1 || savedRows[0].ItemID != "remote-item" || savedRows[0].FailureKind != "post_publish" {
t.Fatalf("远端检查点未保存: rows=%+v err=%v", savedRows, savedErr)
}
// cookieValue、cookieErr 保存平台响应 Cookie 的持久化结果。
cookieValue, cookieErr := store.Cookies.GetValue(ctx, "cid")
if cookieErr != nil || cookieValue != "unb=2; _m_h5_tk=next" {
t.Fatalf("响应 Cookie 未写回: value=%q err=%v", cookieValue, cookieErr)
}
// checkpointPort 使用缺少图片回调的适配器,验证已有远端结果可以直接恢复。
checkpointPort := NewItemBatchPublishPort(store, func() mtop.Client { return client }, nil, nil, nil, nil, nil)
// checkpointOutcome 保存从远端检查点恢复出的应用结果。
// checkpointErr 保存检查点恢复阶段的错误。
checkpointOutcome, checkpointErr := checkpointPort.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(savedRows[0]), "worker-remote")
if checkpointErr != nil || checkpointOutcome.Result == nil || checkpointOutcome.Result.ItemID != "remote-item" {
t.Fatalf("远端检查点重试异常: outcome=%+v err=%v", checkpointOutcome, checkpointErr)
}
if publishCalls != 1 {
t.Fatalf("远端检查点重试不应再次调用平台: calls=%d", publishCalls)
}
}
// TestItemBatchPublishPortRejectsMissingDependencies 验证批量远端适配器缺少端口依赖时快速失败。
func TestItemBatchPublishPortRejectsMissingDependencies(t *testing.T) {
// port 是未配置数据库的批量远端适配器。
port := NewItemBatchPublishPort(nil, nil, nil, nil, nil, func(string, string) ([]byte, string, string, error) { return nil, "", "", nil }, func(context.Context, string) ([]byte, string, error) { return nil, "", nil })
// _, publishErr 保存依赖校验错误。
_, publishErr := port.PublishRemoteRow(context.Background(), 1, itemapp.BatchRow{BatchID: "batch"}, "worker")
if publishErr == nil {
t.Fatal("缺少数据库时不应伪装批量远端发布成功")
}
}
+414
View File
@@ -0,0 +1,414 @@
package adapter
import (
"context"
"encoding/json"
"errors"
"os"
"strings"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
// ItemBatchRepository 将商品批量发布数据库仓储适配为应用层 worker Port。
type ItemBatchRepository struct {
// store 保存数据库聚合入口;批量 worker 不会接触该字段。
store *db.Store
}
// NewItemBatchRepository 构造商品批量发布 worker 的数据库适配器。
func NewItemBatchRepository(store *db.Store) *ItemBatchRepository {
return &ItemBatchRepository{store: store}
}
// CreateBatch 将应用预检模型转换为数据库批次并在单事务内写入。
func (r *ItemBatchRepository) CreateBatch(ctx context.Context, batch itemapp.BatchPreviewPersistenceBatch, rows []itemapp.BatchPreviewRow) error {
// err 表示批次仓储依赖校验错误。
if err := r.validate(); err != nil {
return err
}
// locationJSON 和 err 分别保存发货地 JSON 与序列化错误。
locationJSON, err := json.Marshal(batch.Location)
if err != nil {
return err
}
// status 保存未显式指定时兼容预检批次的默认状态。
status := batch.Status
if strings.TrimSpace(status) == "" {
status = "preview"
}
// databaseRows 保存转换后的数据库明细行。
databaseRows := make([]db.ItemPublishBatchRow, 0, len(rows))
// row 表示当前待转换的应用预检行。
for _, row := range rows {
// imagesJSON 和 imagesErr 分别保存图片字段 JSON 与序列化错误。
imagesJSON, imagesErr := json.Marshal(row.Images)
if imagesErr != nil {
return imagesErr
}
// categoryJSON 和 categoryErr 分别保存类目字段 JSON 与序列化错误。
categoryJSON, categoryErr := json.Marshal(row.Category)
if categoryErr != nil {
return categoryErr
}
// automationJSON 和 automationErr 分别保存自动化字段 JSON 与序列化错误。
automationJSON, automationErr := json.Marshal(row.Automation)
if automationErr != nil {
return automationErr
}
// rawJSON 和 rawErr 分别保存原始行 JSON 与序列化错误。
rawJSON, rawErr := json.Marshal(row.Raw)
if rawErr != nil {
return rawErr
}
// status、errorMessage 和 failureKind 保存数据库状态、展示错误与失败分类。
status, errorMessage, failureKind := "pending", "", ""
if len(row.Errors) > 0 {
status, errorMessage, failureKind = "failed", strings.Join(row.Errors, ";"), "validation"
}
databaseRows = append(databaseRows, db.ItemPublishBatchRow{
RowNo: row.RowNo, CookieID: row.CookieID, Title: row.Title, Description: row.Description,
Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity,
PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: string(imagesJSON),
CategoryJSON: string(categoryJSON), AutomationJSON: string(automationJSON), Status: status,
ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON),
})
}
return r.store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: batch.ID, UserID: batch.UserID, DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir, LocationJSON: string(locationJSON), Status: status}, databaseRows)
}
// PendingRows 查询批次待处理明细并转换为应用模型。
func (r *ItemBatchRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]itemapp.BatchRow, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return nil, err
}
// rows 保存数据库仓储返回的批量明细。
rows, err := r.store.PublishBatches.PendingRows(ctx, batchID, failedOnly)
if err != nil {
return nil, err
}
// result 保存不暴露数据库类型的应用批量明细。
result := make([]itemapp.BatchRow, 0, len(rows))
// row 表示当前待转换的数据库批次明细。
for _, row := range rows {
result = append(result, batchRowApplicationModel(row))
}
return result, nil
}
// RenewBatchLease 委托数据库延长当前 worker 的批次租约。
func (r *ItemBatchRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt)
}
// GetBatch 查询批次并转换为应用状态模型。
func (r *ItemBatchRepository) GetBatch(ctx context.Context, userID int64, batchID string) (itemapp.BatchInfo, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return itemapp.BatchInfo{}, err
}
// batch 保存按用户隔离后的数据库批次。
batch, err := r.store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return itemapp.BatchInfo{}, err
}
return batchInfoApplicationModel(*batch), nil
}
// ListBatchesForUser 查询用户批次摘要并转换为应用模型。
func (r *ItemBatchRepository) ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]itemapp.BatchInfo, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return nil, err
}
// batches 保存数据库返回的用户批次。
batches, err := r.store.PublishBatches.ListForUser(ctx, userID, limit)
if err != nil {
return nil, err
}
// result 保存不暴露数据库模型的应用批次摘要。
result := make([]itemapp.BatchInfo, 0, len(batches))
// batch 表示当前待转换的数据库批次。
for _, batch := range batches {
result = append(result, batchInfoApplicationModel(batch))
}
return result, nil
}
// ListBatchRows 查询批次全部明细并转换为应用模型。
func (r *ItemBatchRepository) ListBatchRows(ctx context.Context, batchID string) ([]itemapp.BatchRow, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return nil, err
}
// rows 保存数据库返回的批次明细。
rows, err := r.store.PublishBatches.Rows(ctx, batchID)
if err != nil {
return nil, err
}
// result 保存不暴露数据库模型的应用批次明细。
result := make([]itemapp.BatchRow, 0, len(rows))
// row 表示当前待转换的数据库明细。
for _, row := range rows {
result = append(result, batchRowApplicationModel(row))
}
return result, nil
}
// ExpiredUploadBatches 查询已超过上传目录保留期限的批次并转换为应用模型。
func (r *ItemBatchRepository) ExpiredUploadBatches(ctx context.Context, cutoff string, limit int) ([]itemapp.BatchInfo, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return nil, err
}
// batches 保存数据库返回的过期上传批次。
batches, err := r.store.PublishBatches.ExpiredUploads(ctx, cutoff, limit)
if err != nil {
return nil, err
}
// result 保存不暴露数据库模型的应用批次状态。
result := make([]itemapp.BatchInfo, 0, len(batches))
// batch 表示当前待转换的过期批次。
for _, batch := range batches {
result = append(result, batchInfoApplicationModel(batch))
}
return result, nil
}
// RequestCancel 请求批次进入取消状态。
func (r *ItemBatchRepository) RequestCancel(ctx context.Context, batchID string) (string, bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return "", false, err
}
// token、running、requestErr 保存数据库取消请求的结果。
token, running, requestErr := r.store.PublishBatches.RequestCancel(ctx, batchID)
if errors.Is(requestErr, db.ErrPublishBatchChanged) {
return "", false, itemapp.ErrBatchConflict
}
return token, running, requestErr
}
// DeleteBatch 删除用户拥有的批次及其受控上传目录。
func (r *ItemBatchRepository) DeleteBatch(ctx context.Context, userID int64, batchID string) error {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return err
}
// batch 保存删除前的上传目录,路径只在适配器内使用。
batch, err := r.store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return err
}
// err 表示数据库批次及其上传目录删除错误。
if err := r.store.PublishBatches.Delete(ctx, userID, batchID); err != nil {
return err
}
if batch != nil && batch.UploadDir != "" {
return os.RemoveAll(batch.UploadDir)
}
return nil
}
// ResetFailed 重置批次中的可重试失败明细。
func (r *ItemBatchRepository) ResetFailed(ctx context.Context, batchID string) error {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return err
}
return r.store.PublishBatches.ResetFailed(ctx, batchID)
}
// FailClaimedBatch 释放当前 worker 持有的批次租约。
func (r *ItemBatchRepository) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.FailClaimedBatch(ctx, batchID, workerToken)
}
// RecoverableBatches 查询可恢复批次并转换为应用层状态模型。
func (r *ItemBatchRepository) RecoverableBatches(ctx context.Context, now int64, limit int) ([]itemapp.BatchInfo, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return nil, err
}
// batches 保存数据库返回的可恢复批次。
batches, err := r.store.PublishBatches.Recoverable(ctx, now, limit)
if err != nil {
return nil, err
}
// result 保存不暴露数据库类型的应用批次状态。
result := make([]itemapp.BatchInfo, 0, len(batches))
// batch 表示当前待转换的数据库批次。
for _, batch := range batches {
result = append(result, batchInfoApplicationModel(batch))
}
return result, nil
}
// FinalizeExpiredCancellation 收口已经超过租约截止时间的取消请求。
func (r *ItemBatchRepository) FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.FinalizeExpiredCancellation(ctx, batchID, now)
}
// ClaimBatch 抢占批次恢复租约并返回是否成功。
func (r *ItemBatchRepository) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.ClaimBatch(ctx, batchID, workerToken, leaseExpiresAt)
}
// ResetInterrupted 重置可确认由进程中断造成的失败明细。
func (r *ItemBatchRepository) ResetInterrupted(ctx context.Context, batchID string) error {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return err
}
return r.store.PublishBatches.ResetInterrupted(ctx, batchID)
}
// ClaimRow 抢占单条批次明细的 worker 租约。
func (r *ItemBatchRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.ClaimRow(ctx, rowID, workerToken)
}
// BatchStatus 读取批次状态供应用层决定失败分类。
func (r *ItemBatchRepository) BatchStatus(ctx context.Context, batchID string) (string, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return "", err
}
return r.store.PublishBatches.BatchStatus(ctx, batchID)
}
// MarkClaimedRowFailed 保存当前 worker 持有明细的失败结果。
func (r *ItemBatchRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind)
}
// MarkClaimedRowSuccess 保存当前 worker 持有明细的远端成功结果。
func (r *ItemBatchRepository) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.MarkClaimedRowSuccess(ctx, rowID, workerToken, itemID, itemURL, rawJSON)
}
// RecountBatch 重算批次的成功与失败统计。
func (r *ItemBatchRepository) RecountBatch(ctx context.Context, batchID string) error {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return err
}
return r.store.PublishBatches.Recount(ctx, batchID)
}
// FinalizeBatch 尝试收口当前 worker 完成的批次。
func (r *ItemBatchRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return "", false, err
}
return r.store.PublishBatches.FinalizeBatch(ctx, batchID, workerToken)
}
// FinalizeCanceled 收口当前 worker 持有的取消批次。
func (r *ItemBatchRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return false, err
}
return r.store.PublishBatches.FinalizeCanceled(ctx, batchID, workerToken)
}
// FinalizeInterrupted 收口被取消或租约中断的批次。
func (r *ItemBatchRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return "", false, err
}
return r.store.PublishBatches.FinalizeInterrupted(ctx, batchID, workerToken, message)
}
// DeleteUpload 删除批次上传目录并清除数据库中的目录记录。
func (r *ItemBatchRepository) DeleteUpload(ctx context.Context, batchID, uploadDir string) error {
// err 表示适配器依赖校验错误。
if err := r.validate(); err != nil {
return err
}
if uploadDir == "" {
return nil
}
// removeErr 保存上传目录删除结果;即使删除失败也继续清理数据库记录。
removeErr := os.RemoveAll(uploadDir)
// clearErr 保存数据库上传目录字段清理结果。
clearErr := r.store.PublishBatches.ClearUploadDir(ctx, batchID)
if removeErr != nil {
return removeErr
}
return clearErr
}
// validate 检查批量发布数据库适配器的必需依赖。
func (r *ItemBatchRepository) validate() error {
if r == nil || r.store == nil || r.store.PublishBatches == nil {
return errors.New("商品批量发布数据库适配器未初始化")
}
return nil
}
// batchRowApplicationModel 将数据库明细完整转换为应用层批量明细。
func batchRowApplicationModel(row db.ItemPublishBatchRow) itemapp.BatchRow {
return itemapp.BatchRow{
ID: row.ID, BatchID: row.BatchID, RowNo: row.RowNo, CookieID: row.CookieID,
Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice,
Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage,
ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON,
RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL, Status: row.Status,
ErrorMessage: row.ErrorMessage, FailureKind: row.FailureKind, WorkerToken: row.WorkerToken,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}
}
// batchInfoApplicationModel 将数据库批次完整转换为应用层批次状态。
func batchInfoApplicationModel(batch db.ItemPublishBatch) itemapp.BatchInfo {
return itemapp.BatchInfo{
ID: batch.ID, UserID: batch.UserID, Status: batch.Status, WorkerToken: batch.WorkerToken,
DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir,
LocationJSON: batch.LocationJSON, TotalCount: batch.TotalCount, SuccessCount: batch.SuccessCount,
FailedCount: batch.FailedCount, LeaseExpiresAt: batch.LeaseExpiresAt,
CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt,
}
}
// 确保适配器覆盖批量发布 worker 的全部持久化端口。
var _ itemapp.BatchRepository = (*ItemBatchRepository)(nil)
// 确保适配器覆盖批次管理应用服务的全部持久化端口。
var _ itemapp.BatchManagementRepository = (*ItemBatchRepository)(nil)
// 确保适配器实现批量恢复扫描所需的状态端口。
var _ itemapp.BatchRecoveryRepository = (*ItemBatchRepository)(nil)
@@ -0,0 +1,165 @@
package adapter
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
// TestItemBatchRepositoryCreatesPreviewFromApplicationModels 验证预检应用模型到数据库字段的转换。
func TestItemBatchRepositoryCreatesPreviewFromApplicationModels(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// repository 是绑定测试数据库的预检批次适配器。
repository := NewItemBatchRepository(store)
// expectedRaw 保存预检行原始输入,验证 JSON 边界不会丢失字段。
expectedRaw := map[string]any{"title": "应用模型商品"}
// rows 保存一条有效行和一条校验失败行。
rows := []itemapp.BatchPreviewRow{
{RowNo: 2, CookieID: "cid", Title: "应用模型商品", Price: "10", Quantity: 2, Raw: expectedRaw, Category: itemapp.BatchPreviewCategory{CatID: "cat-1"}},
{RowNo: 3, CookieID: "cid", Title: "失败商品", Errors: []string{"标题错误"}},
}
// batch 保存应用层批次元数据。
batch := itemapp.BatchPreviewPersistenceBatch{ID: "preview-adapter", UserID: 1, DefaultCookieID: "cid", Filename: "items.csv", UploadDir: t.TempDir(), Location: itemapp.Location{DivisionID: "3301"}}
// err 保存应用模型落库错误。
if err := repository.CreateBatch(ctx, batch, rows); err != nil {
t.Fatalf("创建预检批次失败: %v", err)
}
// storedBatch、batchErr 保存数据库批次读取结果。
storedBatch, batchErr := store.PublishBatches.Get(ctx, 1, batch.ID)
if batchErr != nil || storedBatch.Status != "preview" || storedBatch.LocationJSON == "{}" {
t.Fatalf("批次字段映射异常: batch=%+v err=%v", storedBatch, batchErr)
}
// storedRows、rowsErr 保存数据库明细读取结果。
storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID)
if rowsErr != nil || len(storedRows) != 2 || storedRows[1].Status != "failed" || storedRows[1].FailureKind != "validation" {
t.Fatalf("明细状态映射异常: rows=%+v err=%v", storedRows, rowsErr)
}
// decodedRaw 保存读取后的原始 JSON 对象。
decodedRaw := map[string]any{}
if json.Unmarshal([]byte(storedRows[0].RawJSON), &decodedRaw) != nil || decodedRaw["title"] != expectedRaw["title"] {
t.Fatalf("原始字段 JSON 映射异常: %s", storedRows[0].RawJSON)
}
}
// TestItemBatchRepositoryRejectsMissingStore 验证批量 worker 适配器缺少数据库时快速失败。
func TestItemBatchRepositoryRejectsMissingStore(t *testing.T) {
// repository 保存未装配数据库的批量仓储适配器。
repository := NewItemBatchRepository(nil)
// ctx 是本测试使用的非取消上下文。
ctx := context.Background()
// rowsErr 保存待处理明细查询的装配错误。
if _, rowsErr := repository.PendingRows(ctx, "batch-1", false); rowsErr == nil {
t.Fatal("缺少数据库时 PendingRows 不应伪装成功")
}
// batchErr 保存批次查询的装配错误。
if _, batchErr := repository.GetBatch(ctx, 1, "batch-1"); batchErr == nil {
t.Fatal("缺少数据库时 GetBatch 不应伪装成功")
}
// deleteErr 保存上传目录清理的装配错误。
if deleteErr := repository.DeleteUpload(ctx, "batch-1", "upload"); deleteErr == nil {
t.Fatal("缺少数据库时 DeleteUpload 不应伪装成功")
}
}
// TestItemBatchRepositoryMapsAndCleansBatch 验证批次行和状态完整映射及上传目录清理。
func TestItemBatchRepositoryMapsAndCleansBatch(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// admin、adminErr 保存测试用户及读取错误。
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
if adminErr != nil {
t.Fatalf("读取测试用户失败: %v", adminErr)
}
// uploadDir 是批次上传目录的临时路径。
uploadDir := filepath.Join(t.TempDir(), "batch-upload")
// err 保存创建上传目录的错误。
if err := os.MkdirAll(uploadDir, 0o750); err != nil {
t.Fatalf("创建上传目录失败: %v", err)
}
// batch 保存待适配的数据库批次。
batch := &db.ItemPublishBatch{
ID: "batch-adapter", UserID: admin.ID, DefaultCookieID: "cid", Filename: "items.csv",
UploadDir: uploadDir, LocationJSON: `{"area":"杭州"}`, Status: "running",
}
// rows 保存待适配的批次明细。
rows := []db.ItemPublishBatchRow{{
RowNo: 2, CookieID: "cid", Title: "标题", Description: "描述", Price: "12.00",
OriginalPrice: "15.00", Quantity: 3, PostageMode: "free", Postage: "0",
ImagesJSON: `["a.jpg"]`, CategoryJSON: `{"cat_id":"1"}`, AutomationJSON: `{"enabled":true}`,
Status: "pending", ItemID: "item-1", ItemURL: "https://example/item-1", ErrorMessage: "",
FailureKind: "", WorkerToken: "worker", RawJSON: `{"ok":true}`,
}}
// err 保存创建测试批次的错误。
if err := store.PublishBatches.Create(ctx, batch, rows); err != nil {
t.Fatalf("创建测试批次失败: %v", err)
}
// repository 是绑定测试数据库的应用 Port 适配器。
repository := NewItemBatchRepository(store)
// pending、pendingErr 保存应用层待处理明细及查询错误。
pending, pendingErr := repository.PendingRows(ctx, batch.ID, false)
if pendingErr != nil || len(pending) != 1 {
t.Fatalf("读取待处理明细异常:rows=%+v err=%v", pending, pendingErr)
}
// row 保存已转换的应用明细。
row := pending[0]
if row.RowNo != 2 || row.Title != "标题" || row.ItemID != "item-1" || row.RawJSON != `{"ok":true}` {
t.Fatalf("批次明细映射不完整:%+v", row)
}
// gotBatch、batchErr 保存应用层批次状态及查询错误。
gotBatch, batchErr := repository.GetBatch(ctx, admin.ID, batch.ID)
if batchErr != nil || gotBatch.ID != batch.ID || gotBatch.UserID != admin.ID || gotBatch.UploadDir != uploadDir || gotBatch.LocationJSON != batch.LocationJSON {
t.Fatalf("批次状态映射异常:batch=%+v err=%v", gotBatch, batchErr)
}
// updateErr 保存将批次置为过期状态的测试更新结果。
_, updateErr := store.DB.ExecContext(ctx, `UPDATE item_publish_batches SET status='completed',updated_at='2000-01-01 00:00:00' WHERE id=?`, batch.ID)
if updateErr != nil {
t.Fatalf("设置过期批次失败: %v", updateErr)
}
// expired、expiredErr 保存过期上传批次查询结果。
expired, expiredErr := repository.ExpiredUploadBatches(ctx, "2020-01-01 00:00:00", 10)
if expiredErr != nil || len(expired) != 1 || expired[0].ID != batch.ID || expired[0].UploadDir != uploadDir {
t.Fatalf("过期上传批次映射异常:batches=%+v err=%v", expired, expiredErr)
}
// deleteErr 保存上传目录与数据库字段清理结果。
if deleteErr := repository.DeleteUpload(ctx, batch.ID, uploadDir); deleteErr != nil {
t.Fatalf("清理上传目录失败: %v", deleteErr)
}
// statErr 保存确认上传目录已删除的文件系统错误。
if _, statErr := os.Stat(uploadDir); !os.IsNotExist(statErr) {
t.Fatalf("上传目录仍存在:err=%v", statErr)
}
// clearedBatch、clearedErr 保存清理后的批次记录。
clearedBatch, clearedErr := store.PublishBatches.Get(ctx, admin.ID, batch.ID)
if clearedErr != nil || clearedBatch.UploadDir != "" {
t.Fatalf("数据库上传目录未清理:batch=%+v err=%v", clearedBatch, clearedErr)
}
}
// TestBatchRowApplicationModelPreservesSensitiveFreeBusinessFields 验证明细转换保留业务字段且不引入凭证字段。
func TestBatchRowApplicationModelPreservesSensitiveFreeBusinessFields(t *testing.T) {
// source 保存带有完整业务字段的数据库明细。
source := db.ItemPublishBatchRow{
ID: 4, BatchID: "b", RowNo: 7, CookieID: "cid", Title: "标题", Description: "描述",
Price: "1", OriginalPrice: "2", Quantity: 4, PostageMode: "buyer", Postage: "3",
ImagesJSON: "[]", CategoryJSON: "{}", AutomationJSON: "{}", Status: "failed", ItemID: "i",
ItemURL: "u", ErrorMessage: "失败", FailureKind: "publish", WorkerToken: "w",
RawJSON: "{}", CreatedAt: "created", UpdatedAt: "updated",
}
// converted 保存转换后的应用明细。
converted := batchRowApplicationModel(source)
if converted.ID != source.ID || converted.BatchID != source.BatchID || converted.RowNo != source.RowNo || converted.CookieID != source.CookieID || converted.Title != source.Title || converted.Description != source.Description || converted.Price != source.Price || converted.OriginalPrice != source.OriginalPrice || converted.Quantity != source.Quantity || converted.PostageMode != source.PostageMode || converted.Postage != source.Postage || converted.ImagesJSON != source.ImagesJSON || converted.CategoryJSON != source.CategoryJSON || converted.AutomationJSON != source.AutomationJSON || converted.Status != source.Status || converted.ItemID != source.ItemID || converted.ItemURL != source.ItemURL || converted.ErrorMessage != source.ErrorMessage || converted.FailureKind != source.FailureKind || converted.WorkerToken != source.WorkerToken || converted.RawJSON != source.RawJSON || converted.CreatedAt != source.CreatedAt || converted.UpdatedAt != source.UpdatedAt {
t.Fatalf("明细字段未完整转换:source=%+v converted=%+v", source, converted)
}
}
+124
View File
@@ -0,0 +1,124 @@
package adapter
import (
"context"
"errors"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
// ItemCatalogRepository 将商品读取 Port 适配到数据库商品仓储。
type ItemCatalogRepository struct {
// store 提供商品查询能力。
store *db.Store
}
// NewItemCatalogRepository 创建商品读取数据库适配器。
func NewItemCatalogRepository(store *db.Store) *ItemCatalogRepository {
return &ItemCatalogRepository{store: store}
}
// ListForUser 查询用户范围商品并转换为应用模型。
func (repository *ItemCatalogRepository) ListForUser(ctx context.Context, userID int64, cookieID string) ([]itemapp.CatalogItem, error) {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return nil, errors.New("商品读取存储未初始化")
}
// rows 和 err 保存用户范围商品行及查询错误。
rows, err := repository.store.Items.ListForUser(ctx, userID, cookieID)
if err != nil {
return nil, err
}
return catalogItemsFromRows(rows), nil
}
// ListByCookie 查询账号商品并转换为应用模型。
func (repository *ItemCatalogRepository) ListByCookie(ctx context.Context, cookieID string) ([]itemapp.CatalogItem, error) {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return nil, errors.New("商品读取存储未初始化")
}
// rows 和 err 保存账号商品行及查询错误。
rows, err := repository.store.Items.AllForCookie(ctx, cookieID)
if err != nil {
return nil, err
}
return catalogItemsFromRows(rows), nil
}
// Get 查询单个商品并转换为应用模型。
func (repository *ItemCatalogRepository) Get(ctx context.Context, cookieID, itemID string) (itemapp.CatalogItem, error) {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return itemapp.CatalogItem{}, errors.New("商品读取存储未初始化")
}
// row 和 err 保存单个商品行及查询错误。
row, err := repository.store.Items.Get(ctx, cookieID, itemID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return itemapp.CatalogItem{}, itemapp.ErrCatalogNotFound
}
return itemapp.CatalogItem{}, err
}
return itemapp.CatalogItem{ID: row.ID, CookieID: row.CookieID, ItemID: row.ItemID, ItemTitle: row.ItemTitle, ItemDescription: row.ItemDescription, ItemCategory: row.ItemCategory, ItemPrice: row.ItemPrice, ItemDetail: row.ItemDetail, IsMultiSpec: row.IsMultiSpec, MultiQuantityDelivery: row.MultiQuantityDelivery}, nil
}
// Upsert 创建或完整保存本地商品,并将应用输入转换为数据库行模型。
func (repository *ItemCatalogRepository) Upsert(ctx context.Context, cookieID string, input itemapp.CatalogWriteInput) error {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return errors.New("商品写入存储未初始化")
}
return repository.store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: cookieID, ItemID: input.ItemID, ItemTitle: input.ItemTitle, ItemDescription: input.ItemDescription,
ItemCategory: input.ItemCategory, ItemPrice: input.ItemPrice, ItemDetail: input.ItemDetail,
IsMultiSpec: input.IsMultiSpec, MultiQuantityDelivery: input.MultiQuantityDelivery,
})
}
// UpsertPublishedItem 保存批量发布成功后的商品目录记录。
func (repository *ItemCatalogRepository) UpsertPublishedItem(ctx context.Context, input itemapp.BatchPublishedItem) error {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return errors.New("商品写入存储未初始化")
}
return repository.store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: input.CookieID, ItemID: input.ItemID, ItemTitle: input.ItemTitle, ItemDescription: input.ItemDescription,
ItemCategory: input.ItemCategory, ItemPrice: input.ItemPrice, ItemDetail: input.ItemDetail,
MultiQuantityDelivery: input.MultiQuantityDelivery,
})
}
// Delete 逻辑删除本地商品及其商品级自动化规则。
func (repository *ItemCatalogRepository) Delete(ctx context.Context, cookieID, itemID string) error {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return errors.New("商品写入存储未初始化")
}
return repository.store.Items.Delete(ctx, cookieID, itemID)
}
// SetMultiSpec 更新本地商品的多规格交付开关。
func (repository *ItemCatalogRepository) SetMultiSpec(ctx context.Context, cookieID, itemID string, enabled bool) error {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return errors.New("商品写入存储未初始化")
}
return repository.store.Items.SetMultiSpec(ctx, cookieID, itemID, enabled)
}
// SetMultiQuantity 更新本地商品的多数量交付开关。
func (repository *ItemCatalogRepository) SetMultiQuantity(ctx context.Context, cookieID, itemID string, enabled bool) error {
if repository == nil || repository.store == nil || repository.store.Items == nil {
return errors.New("商品写入存储未初始化")
}
return repository.store.Items.SetMultiQuantity(ctx, cookieID, itemID, enabled)
}
// catalogItemsFromRows 转换数据库商品行并保持查询顺序。
func catalogItemsFromRows(rows []db.ItemInfoRow) []itemapp.CatalogItem {
// items 保存转换后的应用商品模型并保持数据库顺序。
items := make([]itemapp.CatalogItem, 0, len(rows))
// row 表示当前待转换的数据库商品行。
for _, row := range rows {
items = append(items, itemapp.CatalogItem{ID: row.ID, CookieID: row.CookieID, ItemID: row.ItemID, ItemTitle: row.ItemTitle, ItemDescription: row.ItemDescription, ItemCategory: row.ItemCategory, ItemPrice: row.ItemPrice, ItemDetail: row.ItemDetail, IsMultiSpec: row.IsMultiSpec, MultiQuantityDelivery: row.MultiQuantityDelivery})
}
return items
}
var _ itemapp.CatalogRepository = (*ItemCatalogRepository)(nil)
var _ itemapp.CatalogMutationRepository = (*ItemCatalogRepository)(nil)
+92
View File
@@ -0,0 +1,92 @@
package adapter
import (
"context"
"errors"
"testing"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
)
// TestItemCatalogRepositoryRejectsMissingStore 验证商品读取适配器缺少数据库时快速失败。
func TestItemCatalogRepositoryRejectsMissingStore(t *testing.T) {
// repository 保存缺少数据库依赖的商品读取适配器。
repository := NewItemCatalogRepository(nil)
// err 保存用户范围读取的装配错误。
if _, err := repository.ListForUser(context.Background(), 1, "account-1"); err == nil {
t.Fatal("缺少数据库时 ListForUser 不应伪装成功")
}
// err 保存账号范围读取的装配错误。
if _, err := repository.ListByCookie(context.Background(), "account-1"); err == nil {
t.Fatal("缺少数据库时 ListByCookie 不应伪装成功")
}
// err 保存详情读取的装配错误。
if _, err := repository.Get(context.Background(), "account-1", "item-1"); err == nil {
t.Fatal("缺少数据库时 Get 不应伪装成功")
}
// writeErr 保存创建商品时的装配错误。
if writeErr := repository.Upsert(context.Background(), "account-1", itemapp.CatalogWriteInput{ItemID: "item-1"}); writeErr == nil {
t.Fatal("缺少数据库时 Upsert 不应伪装成功")
}
// deleteErr 保存删除商品时的装配错误。
if deleteErr := repository.Delete(context.Background(), "account-1", "item-1"); deleteErr == nil {
t.Fatal("缺少数据库时 Delete 不应伪装成功")
}
// specErr 保存多规格更新时的装配错误。
if specErr := repository.SetMultiSpec(context.Background(), "account-1", "item-1", true); specErr == nil {
t.Fatal("缺少数据库时 SetMultiSpec 不应伪装成功")
}
// quantityErr 保存多数量更新时的装配错误。
if quantityErr := repository.SetMultiQuantity(context.Background(), "account-1", "item-1", true); quantityErr == nil {
t.Fatal("缺少数据库时 SetMultiQuantity 不应伪装成功")
}
}
// TestCatalogItemsFromRowsConvertsAllFields 验证数据库商品行完整转换为应用模型。
func TestCatalogItemsFromRowsConvertsAllFields(t *testing.T) {
// rows 保存带有全部业务字段的数据库商品行。
rows := []db.ItemInfoRow{{ID: 9, CookieID: "account-1", ItemID: "item-1", ItemTitle: "标题", ItemDescription: "描述", ItemCategory: "cat", ItemPrice: "1.00", ItemDetail: "{}", IsMultiSpec: true, MultiQuantityDelivery: true}}
// items 保存适配器转换后的商品模型。
items := catalogItemsFromRows(rows)
if len(items) != 1 || items[0].ID != 9 || items[0].CookieID != "account-1" || !items[0].IsMultiSpec || !items[0].MultiQuantityDelivery {
t.Fatalf("catalogItemsFromRows()=%+v", items)
}
}
// TestItemCatalogRepositoryWritesAndDeletesItem 验证商品写适配器覆盖创建、开关更新和逻辑删除。
func TestItemCatalogRepositoryWritesAndDeletesItem(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的商品读写适配器。
repository := NewItemCatalogRepository(store)
// ctx 是本测试共用的非取消上下文。
ctx := context.Background()
// upsertErr 保存创建商品的写入错误。
upsertErr := repository.Upsert(ctx, "cid", itemapp.CatalogWriteInput{ItemID: "item-write", ItemTitle: "商品", IsMultiSpec: true})
if upsertErr != nil {
t.Fatalf("Upsert error: %v", upsertErr)
}
// specErr 保存多规格开关更新错误。
if specErr := repository.SetMultiSpec(ctx, "cid", "item-write", false); specErr != nil {
t.Fatalf("SetMultiSpec error: %v", specErr)
}
// quantityErr 保存多数量开关更新错误。
if quantityErr := repository.SetMultiQuantity(ctx, "cid", "item-write", true); quantityErr != nil {
t.Fatalf("SetMultiQuantity error: %v", quantityErr)
}
// row、getErr 保存开关更新后的商品记录。
row, getErr := store.Items.Get(ctx, "cid", "item-write")
if getErr != nil || row.IsMultiSpec || !row.MultiQuantityDelivery {
t.Fatalf("商品写入或开关更新异常:row=%+v err=%v", row, getErr)
}
// deleteErr 保存逻辑删除错误。
if deleteErr := repository.Delete(ctx, "cid", "item-write"); deleteErr != nil {
t.Fatalf("Delete error: %v", deleteErr)
}
// missingErr 保存删除后再次读取的错误。
if _, missingErr := store.Items.Get(ctx, "cid", "item-write"); !errors.Is(missingErr, db.ErrNotFound) {
t.Fatalf("删除后商品应不可见,err=%v", missingErr)
}
}
+300
View File
@@ -0,0 +1,300 @@
package adapter
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// ItemPublishPort 将 MTOP、Cookie 会话与运行时同步适配为商品发布端口。
type ItemPublishPort struct {
// store 提供平台凭证读取、凭证锁和 Cookie 写回能力。
store *db.Store
// client 返回商品发布平台客户端,允许运行时注入测试客户端。
client func() mtop.Client
// logger 记录不含凭证内容的发布适配阶段信息。
logger *slog.Logger
// updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。
updateRunningCookie func(context.Context, string, string)
// recoverExpiredSession 在平台报告会话过期时触发账号恢复。
recoverExpiredSession func(context.Context, string, error)
}
// NewItemPublishPort 构造单商品发布基础设施端口。
func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemPublishPort {
// resolvedLogger 保存可用于记录发布适配错误的日志器。
resolvedLogger := logger
if resolvedLogger == nil {
resolvedLogger = slog.Default()
}
return &ItemPublishPort{store: store, client: client, logger: resolvedLogger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession}
}
// categoryRecommender 是 MTOP 类目推荐能力的适配器内部契约。
type categoryRecommender interface {
// RecommendPublishCategory 根据关键词返回平台类目及可能刷新的 Cookie。
RecommendPublishCategory(context.Context, string, string) (mtop.PublishCategory, string, error)
}
// RecommendCategory 读取账号平台凭证、调用类目推荐并提交响应会话变化。
func (p *ItemPublishPort) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (itemapp.BatchPreviewCategory, error) {
if p == nil || p.store == nil || p.store.Cookies == nil {
return itemapp.BatchPreviewCategory{}, errors.New("商品发布存储未初始化")
}
// recommender 和 ok 表示当前 MTOP 客户端是否支持类目推荐。
recommender, ok := p.mtopClient().(categoryRecommender)
if !ok {
return itemapp.BatchPreviewCategory{}, itemapp.ErrCategoryUnsupported
}
// unlock 保护凭证快照读取,远端调用前会释放该锁。
unlock := p.store.LockAccountCredentials(cookieID)
// latest 和 loadErr 保存账号平台凭证视图及读取错误。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if loadErr != nil || latest.UserID != userID || !hasStoredCredential(latest) {
unlock()
return itemapp.BatchPreviewCategory{}, itemapp.ErrCategoryCredentialChanged
}
// requestCtx 和 cancel 控制类目推荐远端调用的最长时间。
requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// mtopCtx 和 cookieSession 保存带凭证快照的平台上下文及会话。
mtopCtx, cookieSession := withCookieSnapshot(requestCtx, latest)
// initialValue 和 initialMetadata 保存远端调用前的凭证版本。
initialValue, initialMetadata := latest.Value, latest.MetadataJSON
unlock()
// category、updatedCookies 和 callErr 保存平台推荐结果、刷新 Cookie 与调用错误。
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, strings.TrimSpace(keyword))
// runtimeCookie 和 persistErr 保存会话写回后的运行时 Cookie 与错误。
runtimeCookie, persistErr := p.persistCategorySession(ctx, userID, cookieID, initialValue, initialMetadata, cookieSession, updatedCookies)
if runtimeCookie != "" && p.updateRunningCookie != nil {
p.updateRunningCookie(ctx, cookieID, runtimeCookie)
}
if persistErr != nil {
return itemapp.BatchPreviewCategory{}, errors.Join(itemapp.ErrCategoryPersistence, persistErr)
}
if callErr != nil {
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
return itemapp.BatchPreviewCategory{}, errors.Join(itemapp.ErrCategoryUnrecognized, callErr)
}
return itemapp.BatchPreviewCategory{}, callErr
}
return itemapp.BatchPreviewCategory{CatID: category.CatID, CatName: category.CatName, ChannelCatID: category.ChannelCatID, TBCatID: category.TBCatID}, nil
}
// persistCategorySession 在远端调用后复核凭证并保存完整会话或平面 Cookie。
func (p *ItemPublishPort) persistCategorySession(ctx context.Context, userID int64, cookieID, initialValue, initialMetadata string, session *mtop.CookieSession, updatedCookies string) (string, error) {
// unlock 保护远端调用完成后的凭证复核与会话写回。
unlock := p.store.LockAccountCredentials(cookieID)
defer unlock()
// latest 和 loadErr 保存远端调用后的凭证视图及读取错误。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if loadErr != nil || latest.UserID != userID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata {
return "", itemapp.ErrCategoryCredentialChanged
}
// value、valueChanged、handled 和 persistErr 保存会话转换结果及写回错误。
value, valueChanged, handled, persistErr := p.persistSession(ctx, latest, session)
if persistErr != nil {
return "", persistErr
}
if handled && valueChanged {
return value, nil
}
if !handled && updatedCookies != "" && updatedCookies != latest.Value {
// err 表示平面 Cookie 写回错误。
if err := p.store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return "", err
}
return updatedCookies, nil
}
return "", nil
}
// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。
func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) {
if p == nil || p.store == nil || p.store.Cookies == nil {
return itemapp.PublishOutcome{}, errors.New("商品发布存储未初始化")
}
// unlock 保护账号凭证快照读取与远端调用后的提交复核。
unlock := p.store.LockAccountCredentials(input.CookieID)
// latest、loadErr 保存加锁后读取的平台凭证视图。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, input.CookieID)
if loadErr != nil || latest.UserID != input.UserID || !hasStoredCredential(latest) {
unlock()
return itemapp.PublishOutcome{}, errors.New("账号凭证已变化,请重试")
}
// requestCtx、cancel 控制单商品平台发布的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
// images 保存应用图片转换后的平台图片请求。
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 保存应用发货地转换后的平台位置请求。
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 := withCookieSnapshot(requestCtx, latest)
// initialValue、initialMetadata 保存远端调用前的凭证快照,用于提交阶段复核。
initialValue, initialMetadata := latest.Value, latest.MetadataJSON
// unlock 在远端调用前释放,避免慢速平台 I/O 占用账号凭证锁。
unlock()
// result、callErr 保存平台发布结果及调用错误。
result, callErr := p.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,
})
// callErr 由适配器转换为应用层错误,保留原始错误链供基础设施恢复逻辑使用。
callErr = publishErrorToApplication(callErr)
// runtimeCookie、persistErr 保存响应 Cookie 提交后的运行时同步值和错误。
runtimeCookie, persistErr := p.persistPublishSession(ctx, input, initialValue, initialMetadata, cookieSession, result, callErr)
if runtimeCookie != "" && p.updateRunningCookie != nil {
p.updateRunningCookie(ctx, input.CookieID, runtimeCookie)
}
if callErr != nil {
if persistErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
}
p.recoverExpired(ctx, input.CookieID, callErr)
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr
}
if result == nil {
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
}
// publishErrorToApplication 将平台发布错误转换为不依赖平台包的应用错误。
func publishErrorToApplication(err error) error {
if err == nil {
return nil
}
// platformErr 保存平台客户端返回的发布错误;其文本已由平台客户端截断或脱敏。
var platformErr *mtop.PublishError
if !errors.As(err, &platformErr) {
return err
}
return &itemapp.PublishError{
Code: itemapp.PublishErrorCode(platformErr.Code), Ret: append([]string(nil), platformErr.Ret...),
Body: platformErr.Body, Err: err,
}
}
// persistPublishSession 在远端调用结束后复核凭证并保存 Cookie 会话变化。
func (p *ItemPublishPort) persistPublishSession(ctx context.Context, input itemapp.PublishInput, initialValue, initialMetadata string, session *mtop.CookieSession, result *mtop.PublishItemResult, callErr error) (string, error) {
// unlock 保护远端调用完成后的凭证复核和写回。
unlock := p.store.LockAccountCredentials(input.CookieID)
defer unlock()
// latest、loadErr 保存远端调用完成后重新读取的平台凭证视图。
latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, input.CookieID)
if loadErr != nil || latest.UserID != input.UserID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata {
return "", errors.New("账号凭证已变化,请重试")
}
// value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。
value, valueChanged, handled, persistErr := p.persistSession(ctx, latest, session)
if persistErr != nil {
if p.logger != nil {
p.logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr)
}
return "", persistErr
}
if handled && valueChanged {
return value, nil
}
if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value {
// saveErr 保存平台返回新 Cookie 的错误。
if saveErr := p.store.Cookies.UpdateValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil {
return "", saveErr
}
return result.UpdatedCookies, nil
}
return "", nil
}
// persistSession 保存完整 Cookie Jar 或平面 Cookie 的会话变化。
func (p *ItemPublishPort) persistSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) {
if session == nil {
return "", false, false, nil
}
// value、snapshot、changed 保存平台会话当前状态。
value, snapshot, changed := session.State()
if !changed {
return detail.Value, false, snapshot != nil, nil
}
// metadata 保存移除旧快照后待写入的新 metadata。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
// err 保存 Cookie 会话持久化错误。
err := p.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
return value, value != detail.Value, true, err
}
// ItemPublishRepository 将本地商品写入适配为应用层商品仓储端口。
type ItemPublishRepository struct {
// store 提供商品基础信息持久化能力。
store *db.Store
}
// NewItemPublishRepository 构造本地商品发布仓储适配器。
func NewItemPublishRepository(store *db.Store) *ItemPublishRepository {
return &ItemPublishRepository{store: store}
}
// Upsert 保存应用层商品记录,并转换为数据库行模型。
func (r *ItemPublishRepository) Upsert(ctx context.Context, record itemapp.ItemRecord) error {
if r == nil || r.store == nil || r.store.Items == nil {
return errors.New("商品发布存储未初始化")
}
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,
})
}
// mtopClient 返回当前商品发布使用的平台客户端,并在测试构造缺失时提供默认实现。
func (p *ItemPublishPort) mtopClient() mtop.Client {
if p != nil && p.client != nil {
// client 保存当前回调返回的平台客户端。
if client := p.client(); client != nil {
return client
}
}
return mtop.NewClient()
}
// recoverExpired 在平台会话过期时通知账号恢复协调器。
func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) {
if p != nil && p.recoverExpiredSession != nil && err != nil {
p.recoverExpiredSession(ctx, cookieID, err)
}
}
// 确保发布端口和仓储实现覆盖应用层定义的最小接口。
var _ itemapp.PublishPort = (*ItemPublishPort)(nil)
var _ itemapp.ItemRepository = (*ItemPublishRepository)(nil)
+75
View File
@@ -0,0 +1,75 @@
package adapter
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"xianyu-go/internal/xianyu/mtop"
)
// ReadPublishImageFile 是批量发布图片本地读取回调;实现方负责路径安全和图片格式校验。
type ReadPublishImageFile func(uploadDir, ref string) ([]byte, string, string, error)
// DownloadPublishImageURL 是批量发布远程图片下载回调;实现方负责 URL 安全、超时和响应大小限制。
type DownloadPublishImageURL func(context.Context, string) ([]byte, string, error)
// LoadBatchPublishImages 解析批次图片引用并转换为平台发布图片模型。
// 文件读取和远程下载通过回调注入,避免应用/适配器层重复拥有网络或文件安全策略。
func LoadBatchPublishImages(ctx context.Context, uploadDir, imagesJSON string, readLocal ReadPublishImageFile, downloadRemote DownloadPublishImageURL) ([]mtop.PublishImage, error) {
if readLocal == nil || downloadRemote == nil {
return nil, errors.New("批量发布图片读取端口未初始化")
}
// refs 保存持久化图片 JSON 中的本地路径或远程 URL 引用。
var refs []string
// err 表示持久化图片引用 JSON 无法解析,调用方应将其作为批次数据损坏处理。
if err := json.Unmarshal([]byte(imagesJSON), &refs); err != nil {
return nil, fmt.Errorf("图片字段格式错误")
}
if len(refs) == 0 {
return nil, errors.New("至少上传 1 张商品图片")
}
// images 保存经过读取回调校验、可交给平台发布端口的图片数据。
images := make([]mtop.PublishImage, 0, len(refs))
// ref 表示当前遍历的图片引用。
for _, ref := range refs {
// data、contentType 和 filename 保存当前图片的内容、媒体类型及展示文件名。
var data []byte
// contentType 保存当前图片的媒体类型。
var contentType string
// filename 保存当前图片交给平台时使用的文件名。
var filename string
// err 保存当前图片读取或下载失败的原因。
var err error
if isPublishImageHTTPURL(ref) {
data, contentType, err = downloadRemote(ctx, ref)
filename = publishImagePathBase(ref)
} else {
data, contentType, filename, err = readLocal(uploadDir, ref)
}
if err != nil {
return nil, err
}
images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data})
}
return images, nil
}
// isPublishImageHTTPURL 判断图片引用是否为远程 HTTP(S) 地址;具体网络访问由调用方回调执行。
func isPublishImageHTTPURL(ref string) bool {
ref = strings.TrimSpace(strings.ToLower(ref))
return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://")
}
// publishImagePathBase 从远程 URL 提取稳定文件名,缺少路径名时使用通用图片名。
func publishImagePathBase(rawURL string) string {
// base 保存从 URL 路径提取出的文件名;空路径回退到通用图片名。
base := filepath.Base(strings.Split(rawURL, "?")[0])
if base == "." || base == "/" || base == "" {
return "image.jpg"
}
return base
}
@@ -0,0 +1,67 @@
package adapter
import (
"context"
"testing"
)
// TestLoadBatchPublishImagesConvertsLocalAndRemoteRefs 验证本地与远程图片回调均转换为平台模型。
func TestLoadBatchPublishImagesConvertsLocalAndRemoteRefs(t *testing.T) {
// localCalls、remoteCalls 记录两类图片读取回调的调用次数。
localCalls, remoteCalls := 0, 0
// readLocal 返回本地图片测试数据和稳定文件名。
readLocal := func(_ string, ref string) ([]byte, string, string, error) {
localCalls++
return []byte("local"), "image/png", ref, nil
}
// downloadRemote 返回远程图片测试数据。
downloadRemote := func(_ context.Context, _ string) ([]byte, string, error) {
remoteCalls++
return []byte("remote"), "image/jpeg", nil
}
// images、loadErr 保存图片转换结果和执行错误。
images, loadErr := LoadBatchPublishImages(context.Background(), "/tmp/upload", `["local.png","https://example.test/remote.jpg?x=1"]`, readLocal, downloadRemote)
if loadErr != nil {
t.Fatalf("加载图片失败: %v", loadErr)
}
if len(images) != 2 || localCalls != 1 || remoteCalls != 1 {
t.Fatalf("图片回调或结果异常: images=%+v local=%d remote=%d", images, localCalls, remoteCalls)
}
if images[1].Filename != "remote.jpg" || images[1].ContentType != "image/jpeg" {
t.Fatalf("远程图片元数据异常: %+v", images[1])
}
}
// TestLoadBatchPublishImagesRejectsInvalidInput 验证缺失端口、非法 JSON 和空图片列表均明确失败。
func TestLoadBatchPublishImagesRejectsInvalidInput(t *testing.T) {
// readLocal、downloadRemote 是不应被非法输入调用的测试回调。
readLocal := func(string, string) ([]byte, string, string, error) { return nil, "", "", nil }
// downloadRemote 是远程图片测试回调。
downloadRemote := func(context.Context, string) ([]byte, string, error) { return nil, "", nil }
// cases 保存不同非法输入及其预期错误断言。
cases := []struct {
name string
imagesJSON string
readLocal ReadPublishImageFile
wantErr bool
}{
{name: "missing port", imagesJSON: `[]`, wantErr: true},
{name: "bad json", imagesJSON: "not-json", readLocal: readLocal, wantErr: true},
{name: "empty", imagesJSON: `[]`, readLocal: readLocal, wantErr: true},
}
// testCase 描述当前非法图片输入分支。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// remote 是当前分支可用的远程下载回调,缺失端口分支故意传入 nil。
remote := downloadRemote
if testCase.readLocal == nil {
remote = nil
}
// _, loadErr 保存当前非法输入的执行错误。
_, loadErr := LoadBatchPublishImages(context.Background(), "/tmp/upload", testCase.imagesJSON, testCase.readLocal, remote)
if (loadErr != nil) != testCase.wantErr {
t.Fatalf("错误断言不符: %v", loadErr)
}
})
}
}
+199
View File
@@ -0,0 +1,199 @@
package adapter
import (
"context"
"errors"
"testing"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/xianyu/mtop"
)
// itemPublishClientStub 是单商品发布端口测试使用的平台客户端替身。
type itemPublishClientStub struct {
// mtop.Client 提供未涉及本测试的方法默认实现。
mtop.Client
// publish 保存单商品发布请求的可控行为。
publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error)
// recommend 保存类目推荐请求的可控行为。
recommend func(context.Context, string, string) (mtop.PublishCategory, string, error)
}
// PublishItem 调用测试注入的单商品发布行为。
func (c itemPublishClientStub) PublishItem(ctx context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return c.publish(ctx, cookies, request)
}
// RecommendPublishCategory 调用测试注入的类目推荐行为。
func (c itemPublishClientStub) RecommendPublishCategory(ctx context.Context, cookies, keyword string) (mtop.PublishCategory, string, error) {
return c.recommend(ctx, cookies, keyword)
}
// unsupportedItemPublishClient 是不提供类目推荐能力的平台客户端替身。
type unsupportedItemPublishClient struct{ mtop.Client }
// TestItemPublishPortRecommendsCategoryAndPersistsUpdatedCookie 验证类目推荐和 Cookie 写回。
func TestItemPublishPortRecommendsCategoryAndPersistsUpdatedCookie(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// client 是返回类目及刷新 Cookie 的平台替身。
client := itemPublishClientStub{recommend: func(_ context.Context, cookies, keyword string) (mtop.PublishCategory, string, error) {
if cookies == "" || keyword != "资料" {
t.Fatalf("推荐请求参数异常: cookies=%q keyword=%q", cookies, keyword)
}
return mtop.PublishCategory{CatID: "cat-1", CatName: "资料", ChannelCatID: "channel-1"}, "unb=2; _m_h5_tk=tk2;", nil
}}
// port 是绑定测试数据库和平台替身的商品发布端口。
port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, nil)
// category、err 保存类目推荐结果。
category, err := port.RecommendCategory(context.Background(), 1, "cid", "资料")
if err != nil || category.CatID != "cat-1" {
t.Fatalf("类目推荐失败: category=%+v err=%v", category, err)
}
// value、valueErr 保存平台返回 Cookie 的本地持久化结果。
value, valueErr := store.Cookies.GetValue(context.Background(), "cid")
if valueErr != nil || value != "unb=2; _m_h5_tk=tk2;" {
t.Fatalf("类目推荐 Cookie 未保存: value=%q err=%v", value, valueErr)
}
}
// TestItemPublishPortRejectsUnsupportedCategoryRecommendation 验证未实现平台能力时返回应用错误。
func TestItemPublishPortRejectsUnsupportedCategoryRecommendation(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// port 是返回不支持能力客户端的商品发布端口。
port := NewItemPublishPort(store, func() mtop.Client { return unsupportedItemPublishClient{} }, nil, nil, nil)
// err 保存能力缺失错误。
_, err := port.RecommendCategory(context.Background(), 1, "cid", "资料")
if !errors.Is(err, itemapp.ErrCategoryUnsupported) {
t.Fatalf("未返回能力缺失错误: %v", err)
}
}
// TestItemPublishPortReleasesCredentialLockDuringRemoteCall 验证单商品发布远端调用期间不占用凭证锁。
func TestItemPublishPortReleasesCredentialLockDuringRemoteCall(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// started 表示平台发布已进入慢速调用阶段。
started := make(chan struct{})
// release 控制测试平台调用继续返回。
release := make(chan struct{})
// client 是带阻塞控制的单商品发布平台替身。
client := itemPublishClientStub{publish: func(_ context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
if cookies == "" || request.Quantity != 2 {
t.Fatalf("发布请求未携带预期凭证或库存:cookies=%q quantity=%d", cookies, request.Quantity)
}
close(started)
<-release
return &mtop.PublishItemResult{ItemID: "published-1", UpdatedCookies: "unb=2; _m_h5_tk=tk2;"}, nil
}}
// port 是绑定测试数据库和平台替身的发布适配器。
port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, nil)
// result 保存异步发布调用的结果。
result := make(chan struct {
outcome itemapp.PublishOutcome
err error
}, 1)
go func() {
// outcome、err 保存发布适配器返回的结果及错误。
outcome, err := port.Publish(context.Background(), itemapp.PublishInput{UserID: 1, CookieID: "cid", Quantity: 2})
result <- struct {
outcome itemapp.PublishOutcome
err error
}{outcome: outcome, err: err}
}()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("平台发布未进入阻塞阶段")
}
// lockAcquired 表示并行操作已取得同账号凭证锁。
lockAcquired := make(chan struct{})
go func() {
// unlock 释放并行测试操作取得的凭证锁。
unlock := store.LockAccountCredentials("cid")
close(lockAcquired)
unlock()
}()
select {
case <-lockAcquired:
case <-time.After(time.Second):
t.Fatal("远端发布期间凭证锁仍被占用")
}
close(release)
select {
// completed 保存发布 goroutine 返回的结果和错误。
case completed := <-result:
if completed.err != nil || completed.outcome.Result == nil || completed.outcome.Result.ItemID != "published-1" {
t.Fatalf("发布结果异常:outcome=%+v err=%v", completed.outcome, completed.err)
}
case <-time.After(3 * time.Second):
t.Fatal("发布适配器未收束")
}
// value、valueErr 保存平台返回 Cookie 的本地持久化结果。
value, valueErr := store.Cookies.GetValue(context.Background(), "cid")
if valueErr != nil || value != "unb=2; _m_h5_tk=tk2;" {
t.Fatalf("平台返回 Cookie 未保存:value=%q err=%v", value, valueErr)
}
}
// TestItemPublishRepositoryUpsertMapsApplicationRecord 验证商品仓储适配器正确转换应用记录。
func TestItemPublishRepositoryUpsertMapsApplicationRecord(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试数据库的商品仓储适配器。
repository := NewItemPublishRepository(store)
// err 保存应用商品记录写入结果。
err := repository.Upsert(context.Background(), itemapp.ItemRecord{CookieID: "cid", ItemID: "local-1", ItemTitle: "商品", ItemDescription: "描述", ItemCategory: "cat", ItemPrice: "12.00", ItemDetail: `{"quantity":2}`, MultiQuantityDelivery: true})
if err != nil {
t.Fatalf("Upsert error: %v", err)
}
// record、recordErr 保存数据库读取到的商品记录。
record, recordErr := store.Items.Get(context.Background(), "cid", "local-1")
if recordErr != nil || record == nil || record.ItemTitle != "商品" || !record.MultiQuantityDelivery {
t.Fatalf("商品记录转换异常:record=%+v err=%v", record, recordErr)
}
}
// TestPublishErrorToApplicationMapsPlatformError 验证发布适配器转换错误时保留分类和原始错误链。
func TestPublishErrorToApplicationMapsPlatformError(t *testing.T) {
// platformErr 是平台客户端返回的库存权限错误替身。
platformErr := &mtop.PublishError{
Code: mtop.PublishErrorStockPermissionMissing,
Ret: []string{"库存权限缺失"},
}
// convertedErr 是适配器转换后的应用层错误。
convertedErr := publishErrorToApplication(platformErr)
// applicationErr 是转换结果中的应用层发布错误。
var applicationErr *itemapp.PublishError
if !errors.As(convertedErr, &applicationErr) {
t.Fatalf("未转换为应用发布错误: %v", convertedErr)
}
if applicationErr.Code != itemapp.PublishErrorStockPermissionMissing || applicationErr.Error() != "库存权限缺失" {
t.Fatalf("应用发布错误分类异常: %+v", applicationErr)
}
// originalErr 是通过应用错误 Unwrap 保留的平台错误。
var originalErr *mtop.PublishError
if !errors.As(convertedErr, &originalErr) || originalErr != platformErr {
t.Fatalf("未保留原始平台错误链: %v", convertedErr)
}
}
// TestPublishErrorToApplicationKeepsNonPlatformError 验证普通基础设施错误不会被错误包装。
func TestPublishErrorToApplicationKeepsNonPlatformError(t *testing.T) {
// plainErr 是不属于平台发布错误类型的基础设施错误。
plainErr := errors.New("transport failed")
// convertedErr 是普通错误经过适配器转换后的结果。
convertedErr := publishErrorToApplication(plainErr)
if convertedErr != plainErr || !errors.Is(convertedErr, plainErr) {
t.Fatalf("普通错误不应被改写: got=%v", convertedErr)
}
if publishErrorToApplication(nil) != nil {
t.Fatal("空错误应保持为空")
}
}
+478
View File
@@ -0,0 +1,478 @@
package adapter
import (
"context"
"errors"
"log/slog"
"strings"
"sync"
"time"
itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// ItemSyncRepository 将商品同步应用 Port 适配到数据库、MTOP 和账号运行时。
type ItemSyncRepository struct {
// store 提供账号凭证和商品持久化能力。
store *db.Store
// client 返回商品列表和详情平台调用能力,允许运行时注入测试客户端。
client func() mtop.Client
// logger 记录不含凭证的同步阶段信息。
logger *slog.Logger
// updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。
updateRunningCookie func(context.Context, string, string)
// recoverExpiredSession 在平台报告会话过期时触发账号恢复。
recoverExpiredSession func(context.Context, string, error)
// cacheMu 保护商品多规格探测缓存。
cacheMu sync.Mutex
// cache 保存短期商品多规格探测结果。
cache map[string]itemSpecCacheEntry
}
// itemSpecCacheEntry 保存商品多规格结果及过期时间。
type itemSpecCacheEntry struct {
// isMultiSpec 表示商品是否包含多规格。
isMultiSpec bool
// expiresAt 表示缓存项失效时间。
expiresAt time.Time
}
// NewItemSyncRepository 构造商品同步基础设施适配器。
func NewItemSyncRepository(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemSyncRepository {
if client == nil {
client = func() mtop.Client { return mtop.NewClient() }
}
if logger == nil {
logger = slog.Default()
}
return &ItemSyncRepository{store: store, client: client, logger: logger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession, cache: make(map[string]itemSpecCacheEntry)}
}
// OwnsAccount 按非敏感所有者字段判断用户是否拥有账号。
func (r *ItemSyncRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) {
if r == nil || r.store == nil || r.store.Cookies == nil {
return false, syncStageError(itemapp.SyncErrorPersistence, errors.New("商品同步存储未初始化"))
}
// ownerID、ownerErr 保存只读取账号归属的查询结果。
ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, cookieID)
if errors.Is(ownerErr, db.ErrNotFound) {
return false, nil
}
if ownerErr != nil {
return false, syncStageError(itemapp.SyncErrorPersistence, ownerErr)
}
return ownerID == userID, nil
}
// SyncAll 读取平台商品全集、探测多规格并完成本地 reconcile。
func (r *ItemSyncRepository) SyncAll(ctx context.Context, query itemapp.SyncQuery) (itemapp.SyncAllResult, error) {
// requestCtx、cancel 控制全量同步的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
// latest、cookieValue、requestContext、session、unlock 保存远端请求使用的凭证快照及锁。
latest, cookieValue, requestContext, session, unlock, err := r.begin(requestCtx, query)
if err != nil {
return itemapp.SyncAllResult{}, err
}
// unlock 在创建完整 Cookie 会话后立即释放,避免慢速平台 I/O 占用账号锁。
unlock()
// result、callErr 保存平台全集结果和调用错误。
result, callErr := r.mtopClient().FetchAllItems(requestContext, cookieValue, query.PageSize, query.MaxPages)
// latest、session 和 callErr 通过重新加锁的提交阶段处理平台 Cookie 变化。
latest, session, callErr, err = r.finishRemote(requestCtx, query, latest, session, callErr)
if err != nil {
return itemapp.SyncAllResult{}, err
}
if callErr != nil {
r.recoverExpired(requestCtx, query.CookieID, callErr)
return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, callErr)
}
if result == nil {
return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, errors.New("商品列表接口未返回结果"))
}
// detailCookies 保存规格探测使用的最新 Cookie 串。
detailCookies := cookieValue
if result.UpdatedCookies != "" {
detailCookies = result.UpdatedCookies
}
// detailErr 保存远端多规格探测错误。
detailErr := r.enrichMultiSpec(requestCtx, detailCookies, query.CookieID, result.Items)
if detailErr != nil {
r.recoverExpired(requestCtx, query.CookieID, detailErr)
return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, detailErr)
}
// persistErr 保存探测后 Cookie 会话提交错误。
persistErr := r.persistAfterEnrich(requestCtx, query, latest, session, cookieValue, result.UpdatedCookies)
if persistErr != nil {
return itemapp.SyncAllResult{}, persistErr
}
// syncResult、syncErr 保存本地全集 reconcile 结果及错误。
syncResult, syncErr := r.syncItems(requestCtx, query.CookieID, result.Items)
if syncErr != nil {
return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPersistence, syncErr)
}
return itemapp.SyncAllResult{TotalCount: len(result.Items), TotalPages: result.TotalPages, SavedCount: syncResult.Saved, DeletedCount: syncResult.Deleted}, nil
}
// SyncPage 读取平台指定页、探测多规格并保存本页商品。
func (r *ItemSyncRepository) SyncPage(ctx context.Context, query itemapp.SyncQuery) (itemapp.SyncPageResult, error) {
// requestCtx、cancel 控制分页同步的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
// latest、cookieValue、requestContext、session、unlock 保存远端请求使用的凭证快照及锁。
latest, cookieValue, requestContext, session, unlock, err := r.begin(requestCtx, query)
if err != nil {
return itemapp.SyncPageResult{}, err
}
unlock()
// result、callErr 保存平台分页结果和调用错误。
result, callErr := r.mtopClient().FetchItemsPage(requestContext, cookieValue, query.PageNumber, query.PageSize)
// latest、session 和 callErr 通过提交阶段处理平台 Cookie 变化。
latest, session, callErr, err = r.finishRemote(requestCtx, query, latest, session, callErr)
if err != nil {
return itemapp.SyncPageResult{}, err
}
if callErr != nil {
r.recoverExpired(requestCtx, query.CookieID, callErr)
return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, callErr)
}
if result == nil {
return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, errors.New("商品列表接口未返回结果"))
}
// detailCookies 保存规格探测使用的最新 Cookie 串。
detailCookies := cookieValue
if result.UpdatedCookies != "" {
detailCookies = result.UpdatedCookies
}
// detailErr 保存远端多规格探测错误。
detailErr := r.enrichMultiSpec(requestCtx, detailCookies, query.CookieID, result.Items)
if detailErr != nil {
r.recoverExpired(requestCtx, query.CookieID, detailErr)
return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, detailErr)
}
// persistErr 保存探测后 Cookie 会话提交错误。
persistErr := r.persistAfterEnrich(requestCtx, query, latest, session, cookieValue, result.UpdatedCookies)
if persistErr != nil {
return itemapp.SyncPageResult{}, persistErr
}
// saved 保存本页成功写入商品的数量。
saved := r.saveItems(requestCtx, query.CookieID, result.Items)
return itemapp.SyncPageResult{PageNumber: result.PageNumber, PageSize: result.PageSize, CurrentCount: len(result.Items), SavedCount: saved}, nil
}
// begin 读取并校验账号平台视图,同时创建本次请求的 Cookie 会话。
func (r *ItemSyncRepository) begin(ctx context.Context, query itemapp.SyncQuery) (*db.CookiePlatformRuntimeData, string, context.Context, *mtop.CookieSession, func(), error) {
if r == nil || r.store == nil || r.store.Cookies == nil || r.store.Items == nil {
return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorPersistence, errors.New("商品同步存储未初始化"))
}
// unlock 保护账号凭证快照的读取和提交。
unlock := r.store.LockAccountCredentials(query.CookieID)
// latest、loadErr 保存平台凭证视图及读取错误。
latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID)
if errors.Is(loadErr, db.ErrNotFound) {
unlock()
return nil, "", ctx, nil, func() {}, itemapp.ErrSyncNotOwned
}
if loadErr != nil {
unlock()
return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorPersistence, loadErr)
}
if latest.UserID != query.UserID {
unlock()
return nil, "", ctx, nil, func() {}, itemapp.ErrSyncNotOwned
}
if !hasStoredCredential(latest) {
unlock()
return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试"))
}
// requestContext、session 保存平台调用需要的 Cookie 会话上下文。
requestContext, session := withCookieSnapshot(ctx, latest)
return &latest, latest.Value, requestContext, session, unlock, nil
}
// finishRemote 在远端调用后重新读取账号并提交 Cookie 会话变化。
func (r *ItemSyncRepository) finishRemote(ctx context.Context, query itemapp.SyncQuery, detail *db.CookiePlatformRuntimeData, session *mtop.CookieSession, callErr error) (*db.CookiePlatformRuntimeData, *mtop.CookieSession, error, error) {
// unlock 保护远端调用完成后的凭证复核和写回。
unlock := r.store.LockAccountCredentials(query.CookieID)
defer unlock()
// latest、loadErr 保存远端调用后的最新账号凭证视图。
latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID)
if loadErr != nil || latest.UserID != query.UserID {
return nil, session, callErr, syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试"))
}
// changed 表示远端调用期间凭证是否被其他流程更新。
changed := latest.Value != detail.Value || latest.MetadataJSON != detail.MetadataJSON
if !changed {
// value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。
_, _, _, persistErr := r.persistSession(ctx, latest, session)
if persistErr != nil {
return nil, session, callErr, syncStageError(itemapp.SyncErrorPersistence, persistErr)
}
}
return &latest, session, callErr, nil
}
// persistAfterEnrich 在多规格探测后复核账号并写回平台 Cookie 变化。
func (r *ItemSyncRepository) persistAfterEnrich(ctx context.Context, query itemapp.SyncQuery, detail *db.CookiePlatformRuntimeData, session *mtop.CookieSession, originalCookie, updatedCookie string) error {
// unlock 保护探测完成后的凭证复核和写回。
unlock := r.store.LockAccountCredentials(query.CookieID)
defer unlock()
// latest、loadErr 保存探测完成后的最新账号凭证视图。
latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID)
if loadErr != nil || latest.UserID != query.UserID {
return syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试"))
}
// changed 表示平台请求期间是否已有其他流程写入凭证。
changed := latest.Value != detail.Value || latest.MetadataJSON != detail.MetadataJSON
if !changed {
// value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。
value, valueChanged, handled, persistErr := r.persistSession(ctx, latest, session)
if persistErr != nil {
return syncStageError(itemapp.SyncErrorPersistence, persistErr)
}
if handled && valueChanged {
r.notifyRunningCookie(ctx, query.CookieID, value)
} else if !handled && updatedCookie != "" && updatedCookie != originalCookie {
// saveErr 保存平台返回的新 Cookie 写回错误。
if saveErr := r.store.Cookies.UpdateValueOwned(ctx, query.CookieID, updatedCookie, query.UserID); saveErr != nil {
return syncStageError(itemapp.SyncErrorPersistence, saveErr)
}
r.notifyRunningCookie(ctx, query.CookieID, updatedCookie)
}
}
return nil
}
// persistSession 保存完整 Cookie Jar 或平面 Cookie 的会话变化。
func (r *ItemSyncRepository) persistSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) {
if session == nil {
return "", false, false, nil
}
// value、snapshot、changed 保存平台会话当前状态。
value, snapshot, changed := session.State()
if !changed {
return detail.Value, false, snapshot != nil, nil
}
// metadata 保存移除旧快照后待写入的新 metadata。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
// err 保存 Cookie 会话持久化错误。
err := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
return value, value != detail.Value, true, err
}
// saveItems 保存分页同步返回的商品基础信息并返回成功数。
func (r *ItemSyncRepository) saveItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) int {
// saved 保存成功写入的商品数量。
saved := 0
// item 表示当前待写入的分页商品。
for _, item := range items {
// price 保存优先使用格式化价格的商品价格文本。
price := item.PriceText
if price == "" {
price = item.Price
}
// saveErr 保存当前商品基础信息写入错误。
saveErr := r.store.Items.UpsertBasic(ctx, &db.ItemInfoRow{CookieID: cookieID, ItemID: item.ID, ItemTitle: item.Title, ItemCategory: item.CategoryID, ItemPrice: price, ItemDetail: item.ItemDetail})
if saveErr != nil {
r.logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", saveErr)
continue
}
if item.IsMultiSpec {
// multiErr 保存当前商品多规格标记写入错误。
if multiErr := r.store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil {
r.logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr)
}
}
saved++
}
return saved
}
// syncItems 将平台商品模型转换为数据库行并执行全集 reconcile。
func (r *ItemSyncRepository) syncItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) {
// rows 保存待写入数据库的商品行。
rows := make([]db.ItemInfoRow, 0, len(items))
// item 表示当前待转换的平台商品。
for _, item := range items {
// price 保存优先使用格式化价格的商品价格文本。
price := item.PriceText
if price == "" {
price = item.Price
}
rows = append(rows, db.ItemInfoRow{CookieID: cookieID, ItemID: item.ID, ItemTitle: item.Title, ItemCategory: item.CategoryID, ItemPrice: price, ItemDetail: item.ItemDetail, IsMultiSpec: item.IsMultiSpec})
}
return r.store.Items.SyncFromRemote(ctx, cookieID, rows)
}
// enrichMultiSpec 使用本地标记和有限并发远端详情探测补全多规格字段。
func (r *ItemSyncRepository) enrichMultiSpec(ctx context.Context, cookies, cookieID string, items []mtop.ItemListItem) error {
// fetcher、ok 保存可选商品详情探测能力及其存在状态。
fetcher, ok := r.mtopClient().(mtop.ItemDetailFetcher)
if !ok {
return nil
}
// itemIDs 保存本次批量读取本地标记的商品标识。
itemIDs := make([]string, 0, len(items))
// item 表示当前待收集标识的平台商品。
for _, item := range items {
itemIDs = append(itemIDs, item.ID)
}
// localFlags、flagsErr 保存本地多规格标记及查询错误。
localFlags, flagsErr := r.store.Items.MultiSpecFlags(ctx, cookieID, itemIDs)
if flagsErr != nil {
r.logger.Warn("批量读取商品多规格标记失败,将继续远端探测", "cookie_id", cookieID, "err", flagsErr)
}
// candidates 保存需要远端探测的商品下标。
candidates := make([]int, 0, len(items))
// index 表示当前商品在结果切片中的下标。
for index := range items {
if items[index].IsMultiSpec || localFlags[items[index].ID] {
items[index].IsMultiSpec = true
r.cacheSpec(cookieID, items[index].ID, true)
continue
}
// cachedValue、cached 表示是否命中短期多规格缓存。
cachedValue, cached := r.cachedSpec(cookieID, items[index].ID)
if cached {
items[index].IsMultiSpec = cachedValue
continue
}
candidates = append(candidates, index)
}
if len(candidates) == 0 {
return nil
}
// probeCtx、cancel 控制批量详情探测的收束。
probeCtx, cancel := context.WithCancel(ctx)
defer cancel()
// semaphore 限制同时进行的详情探测数量。
semaphore := make(chan struct{}, 4)
// waitGroup 等待所有详情探测 goroutine 结束。
var waitGroup sync.WaitGroup
// errorMu 保护 sessionErr 的并发写入。
var errorMu sync.Mutex
// sessionErr 保存首个会话过期错误。
var sessionErr error
// index 表示当前需要启动详情探测的商品下标。
for _, index := range candidates {
waitGroup.Add(1)
go func(index int) {
defer waitGroup.Done()
select {
case semaphore <- struct{}{}:
case <-probeCtx.Done():
return
}
defer func() { <-semaphore }()
// isMultiSpec、detectErr 保存当前商品详情探测结果及错误。
isMultiSpec, detectErr := fetcher.DetectItemMultiSpec(probeCtx, cookies, items[index].ID)
if detectErr != nil {
if mtop.IsSessionExpiredErr(detectErr) {
errorMu.Lock()
if sessionErr == nil {
sessionErr = detectErr
cancel()
}
errorMu.Unlock()
}
return
}
r.cacheSpec(cookieID, items[index].ID, isMultiSpec)
items[index].IsMultiSpec = isMultiSpec
}(index)
}
waitGroup.Wait()
return sessionErr
}
// cachedSpec 读取未过期的多规格探测缓存。
func (r *ItemSyncRepository) cachedSpec(cookieID, itemID string) (bool, bool) {
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
// key 是账号和商品组成的缓存键。
key := cookieID + "\x00" + itemID
// entry、ok 保存缓存项及存在状态。
entry, ok := r.cache[key]
if !ok || time.Now().After(entry.expiresAt) {
delete(r.cache, key)
return false, false
}
return entry.isMultiSpec, true
}
// cacheSpec 写入多规格探测结果并清理已过期缓存。
func (r *ItemSyncRepository) cacheSpec(cookieID, itemID string, value bool) {
if itemID == "" {
return
}
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
if r.cache == nil {
r.cache = make(map[string]itemSpecCacheEntry)
}
// now 是本次缓存清理和写入的时间基准。
now := time.Now()
// key、entry 分别表示待清理的缓存键和缓存项。
for key, entry := range r.cache {
if now.After(entry.expiresAt) {
delete(r.cache, key)
}
}
r.cache[cookieID+"\x00"+itemID] = itemSpecCacheEntry{isMultiSpec: value, expiresAt: now.Add(10 * time.Minute)}
}
// withCookieSnapshot 创建带完整 Cookie Jar 或平面 Cookie 的平台上下文。
func withCookieSnapshot(ctx context.Context, detail db.CookiePlatformRuntimeData) (context.Context, *mtop.CookieSession) {
// snapshot、ok 保存 metadata 中的完整 Cookie Jar 快照及解析状态。
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
return mtop.WithFlatCookieSession(ctx, detail.Value)
}
return mtop.WithCookieSnapshot(ctx, snapshot)
}
// hasStoredCredential 判断账号平台视图是否包含可用 Cookie 凭证。
func hasStoredCredential(detail db.CookiePlatformRuntimeData) bool {
if strings.TrimSpace(detail.Value) != "" {
return true
}
// complete 表示 metadata 是否包含完整 Cookie Jar。
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
// syncStageError 将底层错误包装为不泄露基础设施类型的应用错误。
func syncStageError(kind itemapp.SyncErrorKind, err error) error {
return &itemapp.SyncError{Kind: kind, Err: err}
}
// notifyRunningCookie 将平台返回的 Cookie 更新到运行中的账号实例。
func (r *ItemSyncRepository) notifyRunningCookie(ctx context.Context, cookieID, value string) {
if r.updateRunningCookie != nil && value != "" {
r.updateRunningCookie(ctx, cookieID, value)
}
}
// recoverExpired 在平台会话过期时通知账号恢复协调器。
func (r *ItemSyncRepository) recoverExpired(ctx context.Context, cookieID string, err error) {
if r.recoverExpiredSession != nil && err != nil {
r.recoverExpiredSession(ctx, cookieID, err)
}
}
// mtopClient 返回当前商品同步使用的平台客户端,并在测试构造缺失时提供默认实现。
func (r *ItemSyncRepository) mtopClient() mtop.Client {
if r != nil && r.client != nil {
// client 表示当前回调返回的平台客户端。
if client := r.client(); client != nil {
return client
}
}
return mtop.NewClient()
}
+105
View File
@@ -0,0 +1,105 @@
package adapter
import (
"context"
"fmt"
"sync"
"testing"
"time"
"xianyu-go/internal/xianyu/mtop"
)
// itemSyncDetailClient 是商品详情探测测试使用的平台客户端替身。
type itemSyncDetailClient struct {
// Client 提供商品同步未涉及的平台客户端默认行为。
mtop.Client
// detect 保存测试控制的多规格探测逻辑。
detect func(context.Context, string, string) (bool, error)
}
// DetectItemMultiSpec 执行测试注入的商品多规格探测逻辑。
func (client *itemSyncDetailClient) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) {
return client.detect(ctx, cookies, itemID)
}
// TestItemSyncRepositoryEnrichMultiSpecBoundsConcurrency 验证同步适配器限制探测并发并复用缓存。
func TestItemSyncRepositoryEnrichMultiSpecBoundsConcurrency(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// stateMu 保护远端探测并发统计。
var stateMu sync.Mutex
// active、maxActive、probeCalls 保存当前并发数、峰值并发数和探测次数。
active, maxActive, probeCalls := 0, 0, 0
// client 是带并发统计的商品详情探测替身。
client := &itemSyncDetailClient{detect: func(_ context.Context, cookies, itemID string) (bool, error) {
if cookies == "" || itemID == "" {
t.Fatalf("探测参数缺失:cookies=%q itemID=%q", cookies, itemID)
}
stateMu.Lock()
probeCalls++
active++
if active > maxActive {
maxActive = active
}
stateMu.Unlock()
time.Sleep(20 * time.Millisecond)
stateMu.Lock()
active--
stateMu.Unlock()
return true, nil
}}
// repository 是使用测试数据库和平台替身的商品同步适配器。
repository := NewItemSyncRepository(store, func() mtop.Client { return client }, nil, nil, nil)
// items 保存等待探测的商品列表。
items := make([]mtop.ItemListItem, 8)
// index 表示当前商品在测试列表中的下标。
for index := range items {
items[index].ID = fmt.Sprintf("probe-%d", index)
}
// err 保存首次批量多规格探测的错误。
if err := repository.enrichMultiSpec(context.Background(), "unb=1; _m_h5_tk=t_1;", "cid", items); err != nil {
t.Fatalf("首次多规格探测失败:%v", err)
}
if maxActive > 4 {
t.Fatalf("探测并发=%d,超过上限 4", maxActive)
}
// index、item 分别表示商品下标和探测结果。
for index, item := range items {
if !item.IsMultiSpec {
t.Fatalf("商品 %d 未标记为多规格", index)
}
}
// cachedItems 保存第二次调用使用的商品列表,验证适配器缓存命中。
cachedItems := make([]mtop.ItemListItem, len(items))
// index 表示缓存测试商品下标。
for index := range cachedItems {
cachedItems[index].ID = fmt.Sprintf("probe-%d", index)
}
// err 保存第二次多规格探测的缓存校验错误。
if err := repository.enrichMultiSpec(context.Background(), "unb=1; _m_h5_tk=t_1;", "cid", cachedItems); err != nil {
t.Fatalf("缓存多规格探测失败:%v", err)
}
if probeCalls != len(items) {
t.Fatalf("缓存命中后探测次数=%d,期望=%d", probeCalls, len(items))
}
}
// TestItemSyncRepositorySpecCacheExpires 验证同步适配器过期缓存不会继续返回旧值。
func TestItemSyncRepositorySpecCacheExpires(t *testing.T) {
// repository 是仅用于验证缓存生命周期的零基础设施适配器。
repository := &ItemSyncRepository{cache: map[string]itemSpecCacheEntry{
"cid\x00item-1": {isMultiSpec: true, expiresAt: time.Now().Add(-time.Second)},
}}
// value、ok 保存过期缓存的读取结果。
value, ok := repository.cachedSpec("cid", "item-1")
if ok || value {
t.Fatalf("过期缓存不应命中:value=%v ok=%v", value, ok)
}
repository.cacheSpec("cid", "item-1", false)
value, ok = repository.cachedSpec("cid", "item-1")
if !ok || value {
t.Fatalf("新缓存结果异常:value=%v ok=%v", value, ok)
}
}
+234
View File
@@ -0,0 +1,234 @@
package adapter
import (
"context"
"errors"
keywordsapp "xianyu-go/internal/application/keywords"
"xianyu-go/internal/db"
)
// KeywordRepository 将关键词和指定商品回复数据库操作适配为应用层 Port。
type KeywordRepository struct {
// store 保存数据库聚合入口;敏感账号字段不会被本适配器读取。
store *db.Store
}
// NewKeywordRepository 创建关键词数据库适配器。
func NewKeywordRepository(store *db.Store) *KeywordRepository {
return &KeywordRepository{store: store}
}
// List 查询指定用户账号的关键词规则,并转换为应用模型。
func (r *KeywordRepository) List(ctx context.Context, userID int64, cookieID string) ([]keywordsapp.Keyword, error) {
// err 表示账号归属校验失败,阻止跨用户读取规则。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return nil, err
}
// rows 保存数据库返回的关键词规则行。
rows, err := r.store.Keywords.AllRows(ctx, cookieID)
if err != nil {
return nil, err
}
// result 保存转换后的应用层关键词模型,不携带数据库对象。
result := make([]keywordsapp.Keyword, 0, len(rows))
// row 表示当前待转换的关键词数据库行。
for _, row := range rows {
result = append(result, keywordModel(row))
}
return result, nil
}
// Add 创建一条指定用户账号的关键词规则。
func (r *KeywordRepository) Add(ctx context.Context, userID int64, cookieID string, draft keywordsapp.Draft) (int64, error) {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return 0, err
}
return r.store.Keywords.Add(ctx, cookieID, draft.Keyword, draft.Reply, draft.ItemID, draft.Type, draft.ImageURL)
}
// Replace 原子覆盖指定用户账号的全部关键词规则。
func (r *KeywordRepository) Replace(ctx context.Context, userID int64, cookieID string, drafts []keywordsapp.Draft) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
// rows 保存转换后的数据库关键词写入行。
rows := make([]db.KeywordRow, 0, len(drafts))
// draft 表示当前待转换的应用层关键词草稿。
for _, draft := range drafts {
rows = append(rows, db.KeywordRow{
CookieID: cookieID,
Keyword: draft.Keyword,
Reply: draft.Reply,
ItemID: draft.ItemID,
Type: draft.Type,
ImageURL: draft.ImageURL,
})
}
return r.store.Keywords.ReplaceForCookie(ctx, cookieID, rows)
}
// Update 更新指定用户账号的一条关键词规则。
func (r *KeywordRepository) Update(ctx context.Context, userID int64, cookieID string, id int64, draft keywordsapp.Draft) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
// err 表示数据库更新错误或目标规则不存在。
err := r.store.Keywords.UpdateByID(ctx, db.KeywordRow{
ID: id, CookieID: cookieID, Keyword: draft.Keyword, Reply: draft.Reply,
ItemID: draft.ItemID, Type: draft.Type, ImageURL: draft.ImageURL,
})
if errors.Is(err, db.ErrNotFound) {
return keywordsapp.ErrNotFound
}
return err
}
// DeleteByID 按 ID 删除指定用户账号的一条关键词规则。
func (r *KeywordRepository) DeleteByID(ctx context.Context, userID int64, cookieID string, id int64) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
// err 表示数据库删除错误或目标规则不存在。
err := r.store.Keywords.DeleteByID(ctx, cookieID, id)
if errors.Is(err, db.ErrNotFound) {
return keywordsapp.ErrNotFound
}
return err
}
// DeleteByIndex 按稳定 ID 顺序的零基索引删除关键词规则。
func (r *KeywordRepository) DeleteByIndex(ctx context.Context, userID int64, cookieID string, index int) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
// err 表示数据库删除错误或索引没有对应规则。
err := r.store.Keywords.DeleteByIndex(ctx, cookieID, index)
if errors.Is(err, db.ErrNotFound) {
return keywordsapp.ErrNotFound
}
return err
}
// ListItemReplies 查询当前用户所有账号的商品回复,并保持数据库返回顺序。
func (r *KeywordRepository) ListItemReplies(ctx context.Context, userID int64) ([]keywordsapp.ItemReply, error) {
// err 表示适配器依赖或用户身份校验失败。
if err := r.validateUser(userID); err != nil {
return nil, err
}
// cookieIDs 保存当前用户拥有的账号标识,不包含账号凭证。
cookieIDs, err := r.store.Cookies.ListOwnedIDs(ctx, userID)
if err != nil {
return nil, err
}
// result 保存跨账号聚合后的商品回复应用模型。
result := make([]keywordsapp.ItemReply, 0)
// cookieID 表示当前遍历的用户账号。
for _, cookieID := range cookieIDs {
// queryErr 表示当前账号商品回复读取失败。
// rows 保存当前账号的商品回复数据库行。
rows, queryErr := r.store.ItemReps.AllForUser(ctx, cookieID)
if queryErr != nil {
return nil, queryErr
}
// row 表示当前待转换的商品回复行。
for _, row := range rows {
result = append(result, itemReplyModel(row))
}
}
return result, nil
}
// GetItemReply 读取指定用户账号和商品的商品回复。
func (r *KeywordRepository) GetItemReply(ctx context.Context, userID int64, cookieID, itemID string) (keywordsapp.ItemReply, error) {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return keywordsapp.ItemReply{}, err
}
// row、err 保存商品回复数据库行及读取错误。
row, err := r.store.ItemReps.Get(ctx, cookieID, itemID)
if errors.Is(err, db.ErrNotFound) {
return keywordsapp.ItemReply{}, keywordsapp.ErrNotFound
}
if err != nil {
return keywordsapp.ItemReply{}, err
}
return itemReplyModel(*row), nil
}
// SetItemReply 覆盖指定用户账号和商品的商品回复。
func (r *KeywordRepository) SetItemReply(ctx context.Context, userID int64, cookieID, itemID, content string) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
return r.store.ItemReps.Set(ctx, cookieID, itemID, content)
}
// DeleteItemReply 删除指定用户账号和商品的商品回复。
func (r *KeywordRepository) DeleteItemReply(ctx context.Context, userID int64, cookieID, itemID string) error {
// err 表示账号归属校验失败。
if err := r.authorize(ctx, userID, cookieID); err != nil {
return err
}
return r.store.ItemReps.Delete(ctx, cookieID, itemID)
}
// authorize 只查询账号归属,不读取或解密任何凭证字段。
func (r *KeywordRepository) authorize(ctx context.Context, userID int64, cookieID string) error {
// err 表示适配器依赖或用户身份校验失败。
if err := r.validateUser(userID); err != nil {
return err
}
if cookieID == "" {
return keywordsapp.ErrInvalidInput
}
// owned、err 保存当前用户对账号的直接归属结果及查询错误。
owned, err := r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
if err != nil {
return err
}
if owned {
return nil
}
// ownerID、err 保存账号所有者标识及读取错误,用于区分不存在和跨用户访问。
ownerID, err := r.store.Cookies.GetOwnerID(ctx, cookieID)
if errors.Is(err, db.ErrNotFound) {
return keywordsapp.ErrNotFound
}
if err != nil {
return err
}
if ownerID != userID {
return keywordsapp.ErrForbidden
}
return nil
}
// validateUser 检查数据库适配器和用户身份是否可用。
func (r *KeywordRepository) validateUser(userID int64) error {
if r == nil || r.store == nil || r.store.Cookies == nil || r.store.Keywords == nil || r.store.ItemReps == nil {
return errors.New("关键词数据库适配器未初始化")
}
if userID <= 0 {
return keywordsapp.ErrInvalidUser
}
return nil
}
// keywordModel 将数据库关键词行转换为应用模型。
func keywordModel(row db.KeywordRow) keywordsapp.Keyword {
return keywordsapp.Keyword{ID: row.ID, CookieID: row.CookieID, Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID, Type: row.Type, ImageURL: row.ImageURL}
}
// itemReplyModel 将数据库商品回复行转换为应用模型。
func itemReplyModel(row db.ItemReply) keywordsapp.ItemReply {
return keywordsapp.ItemReply{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent}
}
var _ keywordsapp.Repository = (*KeywordRepository)(nil)
+132
View File
@@ -0,0 +1,132 @@
package adapter
import (
"context"
"errors"
"testing"
keywordsapp "xianyu-go/internal/application/keywords"
)
// TestKeywordRepositoryCRUDMapping 验证关键词和指定商品回复的 SQLite 映射及成功路径。
func TestKeywordRepositoryCRUDMapping(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是待验证的关键词数据库适配器。
repository := NewKeywordRepository(store)
// ctx 是本测试数据库操作共用的非取消上下文。
ctx := context.Background()
// owner 是测试模板中的关键词所有者。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// keywordID、createErr 保存关键词创建结果。
keywordID, createErr := repository.Add(ctx, owner.ID, "cid", keywordsapp.Draft{Keyword: "价格", Reply: "50元", Type: "text", ItemID: "item-1"})
if createErr != nil || keywordID <= 0 {
t.Fatalf("创建关键词失败 id=%d err=%v", keywordID, createErr)
}
// rows、listErr 保存关键词列表结果。
rows, listErr := repository.List(ctx, owner.ID, "cid")
if listErr != nil || len(rows) != 1 || rows[0].Keyword != "价格" {
t.Fatalf("关键词列表异常 rows=%+v err=%v", rows, listErr)
}
// updateErr 保存关键词更新结果。
updateErr := repository.Update(ctx, owner.ID, "cid", keywordID, keywordsapp.Draft{Keyword: "新价格", Reply: "60元", Type: "text"})
if updateErr != nil {
t.Fatal(updateErr)
}
// replaceErr 保存批量替换结果。
replaceErr := repository.Replace(ctx, owner.ID, "cid", []keywordsapp.Draft{{Keyword: "图片", Type: "image", ImageURL: "https://example.invalid/a.png"}})
if replaceErr != nil {
t.Fatal(replaceErr)
}
// replacedRows、replacedErr 保存批量替换后的列表结果。
replacedRows, replacedErr := repository.List(ctx, owner.ID, "cid")
if replacedErr != nil || len(replacedRows) != 1 || replacedRows[0].Type != "image" {
t.Fatalf("替换结果异常 rows=%+v err=%v", replacedRows, replacedErr)
}
// setErr 保存指定商品回复写入结果。
if setErr := repository.SetItemReply(ctx, owner.ID, "cid", "item-1", "专属回复"); setErr != nil {
t.Fatal(setErr)
}
// itemReply、getErr 保存指定商品回复读取结果。
itemReply, getErr := repository.GetItemReply(ctx, owner.ID, "cid", "item-1")
if getErr != nil || itemReply.ReplyContent != "专属回复" {
t.Fatalf("商品回复读取异常 row=%+v err=%v", itemReply, getErr)
}
// itemRows、itemListErr 保存指定商品回复列表结果。
itemRows, itemListErr := repository.ListItemReplies(ctx, owner.ID)
if itemListErr != nil || len(itemRows) != 1 || itemRows[0].CookieID != "cid" {
t.Fatalf("商品回复列表异常 rows=%+v err=%v", itemRows, itemListErr)
}
// deleteReplyErr 保存指定商品回复删除结果。
if deleteReplyErr := repository.DeleteItemReply(ctx, owner.ID, "cid", "item-1"); deleteReplyErr != nil {
t.Fatal(deleteReplyErr)
}
// deleteErr 保存关键词 ID 删除结果。
if deleteErr := repository.DeleteByID(ctx, owner.ID, "cid", keywordID); deleteErr != nil && !errors.Is(deleteErr, keywordsapp.ErrNotFound) {
t.Fatal(deleteErr)
}
}
// TestKeywordRepositoryRejectsCrossUserAccess 验证跨用户账号无法读写关键词或商品回复。
func TestKeywordRepositoryRejectsCrossUserAccess(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试数据库操作共用的非取消上下文。
ctx := context.Background()
// created、createErr 保存第二个用户的创建结果。
created, createErr := store.Users.Create(ctx, "other", "other@example.invalid", "pw")
if createErr != nil || !created {
t.Fatal(createErr)
}
// other 是第二个用户的非敏感身份摘要。
other, otherErr := store.Users.GetByUsername(ctx, "other")
if otherErr != nil {
t.Fatal(otherErr)
}
// saveErr 保存第二个用户账号的创建结果。
if saveErr := store.Cookies.Save(ctx, "other-cid", "cookie", other.ID); saveErr != nil {
t.Fatal(saveErr)
}
// repository 是待验证的关键词数据库适配器。
repository := NewKeywordRepository(store)
// err 保存跨用户读取结果。
_, err := repository.List(ctx, 1, "other-cid")
if !errors.Is(err, keywordsapp.ErrForbidden) {
t.Fatalf("跨用户读取应返回 ErrForbidden,err=%v", err)
}
// writeErr 保存跨用户写入结果。
writeErr := repository.SetItemReply(ctx, 1, "other-cid", "item", "reply")
if !errors.Is(writeErr, keywordsapp.ErrForbidden) {
t.Fatalf("跨用户写入应返回 ErrForbidden,err=%v", writeErr)
}
}
// TestKeywordRepositoryPropagatesInfrastructureErrors 验证数据库故障不伪装为资源不存在。
func TestKeywordRepositoryPropagatesInfrastructureErrors(t *testing.T) {
// store 是随后主动关闭数据库连接的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试存储的关键词适配器。
repository := NewKeywordRepository(store)
// closeErr 保存关闭测试数据库的结果。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// err 保存数据库关闭后的列表结果。
_, err := repository.List(context.Background(), 1, "cid")
if err == nil || errors.Is(err, keywordsapp.ErrNotFound) || errors.Is(err, keywordsapp.ErrForbidden) {
t.Fatalf("数据库故障应原样返回,err=%v", err)
}
// missingErr 保存缺少数据库适配器依赖时的装配错误。
_, missingErr := NewKeywordRepository(nil).List(context.Background(), 1, "cid")
if missingErr == nil {
t.Fatal("缺少 Store 时应返回装配错误")
}
}
var _ keywordsapp.Repository = (*KeywordRepository)(nil)
+198
View File
@@ -0,0 +1,198 @@
package adapter
import (
"context"
"errors"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
)
// NotificationChannelRepository 将通知渠道数据库能力限制在应用层定义的端口内。
type NotificationChannelRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用;配置字段不会进入摘要模型。
store *db.Store
}
// NewNotificationChannelRepository 构造通知渠道应用端口适配器;数据库依赖不完整时返回 nil。
func NewNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository {
if store == nil || store.Notifications == nil || store.Cookies == nil {
return nil
}
return NotificationChannelRepository{store: store}
}
// ListChannels 查询渠道摘要并丢弃敏感配置。
func (r NotificationChannelRepository) 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 NotificationChannelRepository) 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, normalizeNotificationRepositoryError(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 NotificationChannelRepository) 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 NotificationChannelRepository) 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 normalizeNotificationRepositoryError(r.store.Notifications.UpdateChannelForUser(ctx, &row, userID))
}
// DeleteChannel 删除用户拥有的渠道并统一转换资源错误。
func (r NotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID))
}
// OwnsChannel 查询通知渠道归属,不读取配置内容。
func (r NotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) {
return r.store.Notifications.OwnsChannel(ctx, channelID, userID)
}
// OwnsAccount 查询账号归属,不读取或解密 Cookie。
func (r NotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
}
// ListBindings 查询绑定摘要并转换为应用模型。
func (r NotificationChannelRepository) 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 NotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
return r.store.Notifications.AccountBindings(ctx, cookieID)
}
// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。
func (r NotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs))
}
// SetSingleBinding 更新单个账号绑定状态并归一化资源错误。
func (r NotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
return normalizeNotificationRepositoryError(r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled))
}
// DeleteBinding 删除用户的一条绑定并归一化资源错误。
func (r NotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.DeleteBinding(ctx, userID, bindingID))
}
// DeleteAccountBindings 删除用户账号的全部绑定并归一化资源错误。
func (r NotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
return normalizeNotificationRepositoryError(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
}
// NotificationUncertainRepository 将通知不确定状态查询限制在非敏感摘要端口内。
type NotificationUncertainRepository struct {
// store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。
store *db.Store
}
// NewNotificationUncertainRepository 创建通知不确定状态查询适配器;数据库依赖缺失时返回 nil。
func NewNotificationUncertainRepository(store *db.Store) notificationsapp.Repository {
if store == nil || store.Notifications == nil {
return nil
}
return NotificationUncertainRepository{store: store}
}
// ListUncertainForUser 查询指定用户的不确定通知摘要,并转换为应用模型。
func (r NotificationUncertainRepository) 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 NotificationUncertainRepository) CountUncertainForUser(ctx context.Context, userID int64) (int, error) {
return r.store.Notifications.CountUncertainOutboxForUser(ctx, userID)
}
// ListUncertainForAdmin 查询全局不确定通知摘要,并转换为应用模型。
func (r NotificationUncertainRepository) 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 NotificationUncertainRepository) CountUncertainForAdmin(ctx context.Context) (int, error) {
return r.store.Notifications.CountUncertainOutboxForAdmin(ctx)
}
// 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.ChannelRepository = NotificationChannelRepository{}
// 编译期确认通知不确定状态适配器覆盖应用层定义的全部能力。
var _ notificationsapp.Repository = NotificationUncertainRepository{}
@@ -0,0 +1,90 @@
package adapter
import (
"context"
"errors"
"testing"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
)
// TestNotificationChannelRepositoryKeepsConfigOutOfSummaries 验证渠道摘要映射不携带敏感配置。
func TestNotificationChannelRepositoryKeepsConfigOutOfSummaries(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试数据库操作使用的非取消上下文。
ctx := context.Background()
// owner、ownerErr 保存模板管理员及查询错误。
owner, ownerErr := store.Users.GetByUsername(ctx, "admin")
if ownerErr != nil {
t.Fatal(ownerErr)
}
// channelID、createErr 保存带敏感配置的渠道创建结果。
channelID, createErr := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{Name: "邮件", Type: "email", Config: `{"password":"secret"}`, EventTypes: "order", Enabled: true, UserID: owner.ID})
if createErr != nil {
t.Fatal(createErr)
}
// repository 是待验证的通知渠道应用端口适配器。
repository := NewNotificationChannelRepository(store)
// summaries、listErr 保存适配器返回的脱敏渠道列表。
summaries, listErr := repository.ListChannels(ctx, owner.ID)
if listErr != nil || len(summaries) != 1 || summaries[0].ID != channelID {
t.Fatalf("渠道摘要映射异常 summaries=%+v err=%v", summaries, listErr)
}
// record、recordErr 保存更新路径读取的完整配置记录;该值只应停留在应用更新端口内。
record, recordErr := repository.GetChannelForUpdate(ctx, channelID, owner.ID)
if recordErr != nil || record == nil || record.Config == "" {
t.Fatalf("渠道更新记录缺少配置 record=%+v err=%v", record, recordErr)
}
}
// TestNotificationChannelRepositoryMapsMissingResources 验证资源缺失统一转换为应用层渠道错误。
func TestNotificationChannelRepositoryMapsMissingResources(t *testing.T) {
// store 是使用临时 SQLite 数据库的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// ctx 是本测试数据库操作使用的非取消上下文。
ctx := context.Background()
// repository 是待验证的通知渠道应用端口适配器。
repository := NewNotificationChannelRepository(store)
// updateErr 保存更新不存在渠道时的应用层错误。
updateErr := repository.UpdateChannel(ctx, 1, notificationsapp.ChannelRecord{ID: 999, Name: "missing", Type: "webhook"})
if !errors.Is(updateErr, notificationsapp.ErrChannelNotFound) {
t.Fatalf("不存在渠道更新应映射为缺失错误: %v", updateErr)
}
// deleteErr 保存删除不存在渠道时的应用层错误。
deleteErr := repository.DeleteChannel(ctx, 999, 1)
if !errors.Is(deleteErr, notificationsapp.ErrChannelNotFound) {
t.Fatalf("不存在渠道删除应映射为缺失错误: %v", deleteErr)
}
// nilRepository 验证缺少数据库依赖时不会伪造可用端口。
nilRepository := NewNotificationChannelRepository(nil)
if nilRepository != nil {
t.Fatal("缺少 Store 时通知渠道适配器应返回 nil")
}
}
// TestNotificationUncertainRepositoryRejectsClosedStore 验证不确定通知适配器透传基础设施错误且不暴露正文。
func TestNotificationUncertainRepositoryRejectsClosedStore(t *testing.T) {
// store 是随后关闭连接的临时 SQLite 数据库。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 是绑定测试存储的不确定通知适配器。
repository := NewNotificationUncertainRepository(store)
// closeErr 保存关闭测试数据库时的资源错误。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// _, listErr 保存数据库关闭后的普通用户查询错误。
_, listErr := repository.ListUncertainForUser(context.Background(), 1, 10)
if listErr == nil {
t.Fatal("数据库关闭后不确定通知查询应返回基础设施错误")
}
// nilRepository 验证缺少数据库依赖时返回 nil。
nilRepository := NewNotificationUncertainRepository(nil)
if nilRepository != nil {
t.Fatal("缺少 Store 时不确定通知适配器应返回 nil")
}
}
+38
View File
@@ -0,0 +1,38 @@
package adapter
import (
"errors"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// NormalizeOrderError 将数据库订单错误转换为应用层稳定错误,阻止存储错误类型穿过适配边界。
func NormalizeOrderError(err error) error {
if errors.Is(err, db.ErrNotFound) {
return orderapp.ErrNotFound
}
if errors.Is(err, db.ErrForbidden) {
return orderapp.ErrForbidden
}
return err
}
// 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,
}
}
+41
View File
@@ -0,0 +1,41 @@
package adapter
import (
"errors"
"testing"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// TestNormalizeOrderError 验证数据库错误不会越过订单应用适配边界。
func TestNormalizeOrderError(t *testing.T) {
// cases 保存数据库错误到应用错误的映射样例及空错误行为。
cases := []struct {
name string
input error
want error
}{
{name: "not found", input: db.ErrNotFound, want: orderapp.ErrNotFound},
{name: "forbidden", input: db.ErrForbidden, want: orderapp.ErrForbidden},
{name: "wrapped not found", input: errors.Join(errors.New("查询失败"), db.ErrNotFound), want: orderapp.ErrNotFound},
{name: "other", input: errors.New("数据库暂时不可用"), want: nil},
{name: "nil", input: nil, want: nil},
}
// testCase 表示当前错误映射样例。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// got 保存适配器归一化后的错误。
got := NormalizeOrderError(testCase.input)
if testCase.want == nil {
if got != testCase.input {
t.Fatalf("error identity changed: got=%v want=%v", got, testCase.input)
}
return
}
if !errors.Is(got, testCase.want) {
t.Fatalf("error=%v want=%v", got, testCase.want)
}
})
}
}
+36
View File
@@ -0,0 +1,36 @@
package adapter
import (
"context"
"errors"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// OrderReconciliationRepository 将订单应用层补偿 Port 适配为数据库写入。
// 数据库聚合仅在本适配器内部可见,订单应用服务和 Server 运行时不直接访问它。
type OrderReconciliationRepository struct {
// store 保存补偿记录使用的数据库聚合入口。
store *db.Store
}
// NewOrderReconciliationRepository 创建订单补偿记录数据库适配器。
// 缺少 Store 或补偿仓储时返回 nil,由调用方在运行时边界报告装配错误。
func NewOrderReconciliationRepository(store *db.Store) *OrderReconciliationRepository {
if store == nil || store.Reconciliations == nil {
return nil
}
return &OrderReconciliationRepository{store: store}
}
// RecordReconciliation 创建外部动作成功、本地状态待补偿的记录。
func (r *OrderReconciliationRepository) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
if r == nil || r.store == nil || r.store.Reconciliations == nil {
return "", errors.New("订单补偿存储未初始化")
}
return r.store.Reconciliations.CreatePending(ctx, orderID, cookieID, kind, message)
}
// 确保数据库适配器覆盖订单应用层声明的补偿 Port。
var _ orderapp.ReconciliationRecorder = (*OrderReconciliationRepository)(nil)
@@ -0,0 +1,57 @@
package adapter
import (
"context"
"errors"
"testing"
orderapp "xianyu-go/internal/application/orders"
)
// TestOrderReconciliationRepositoryRecordsPending 验证补偿应用模型能写入数据库并返回记录标识。
func TestOrderReconciliationRepositoryRecordsPending(t *testing.T) {
// store、cleanup 保存当前测试使用的 SQLite 存储及资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 保存绑定测试数据库的订单补偿适配器。
repository := NewOrderReconciliationRepository(store)
// recordID、err 保存补偿记录写入结果及错误。
recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "本地写入失败")
if err != nil || recordID == "" {
t.Fatalf("创建补偿记录失败: id=%q err=%v", recordID, err)
}
// records、listErr 保存数据库扫描到的待补偿记录及错误。
records, listErr := store.Reconciliations.ListPending(context.Background(), 10)
if listErr != nil || len(records) != 1 || records[0].ID != recordID || records[0].OrderID != "order-1" || records[0].Kind != "manual_status_ship" {
t.Fatalf("补偿记录映射异常: records=%+v err=%v", records, listErr)
}
}
// TestOrderReconciliationRepositoryRejectsMissingDependency 验证缺少数据库依赖时适配器快速失败。
func TestOrderReconciliationRepositoryRejectsMissingDependency(t *testing.T) {
// repository 保存未装配数据库时返回的空适配器。
repository := NewOrderReconciliationRepository(nil)
// recordID、err 保存缺少依赖时的写入结果。
recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "失败")
if recordID != "" || err == nil {
t.Fatalf("缺少数据库时应返回装配错误: id=%q err=%v", recordID, err)
}
}
// TestOrderReconciliationRepositoryPropagatesPersistenceError 验证数据库关闭后的错误不会被伪装为成功。
func TestOrderReconciliationRepositoryPropagatesPersistenceError(t *testing.T) {
// store、cleanup 保存随后关闭数据库连接的测试存储。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// repository 保存绑定已关闭数据库的订单补偿适配器。
repository := NewOrderReconciliationRepository(store)
// closeErr 表示关闭测试数据库连接时产生的资源释放错误。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatal(closeErr)
}
// recordID、err 保存底层数据库故障的写入结果。
recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "失败")
if recordID != "" || err == nil || errors.Is(err, orderapp.ErrNotFound) {
t.Fatalf("数据库故障应透传持久化错误: id=%q err=%v", recordID, err)
}
}
@@ -1,4 +1,4 @@
package server
package adapter
import (
"context"
@@ -8,24 +8,24 @@ import (
"xianyu-go/internal/db"
)
// storeOrderRepository 将完整 Store 适配为订单应用服务窄 repository。
type storeOrderRepository struct {
// OrderRepository 将数据库 Store 适配为订单应用服务窄 repository。
type OrderRepository struct {
// store 保存数据库聚合入口,仅在适配器内部使用。
store *db.Store
}
// ExistsOwned 委托账号归属查询。
func (r storeOrderRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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,
@@ -97,7 +97,7 @@ func platformRuntimeDataFromDB(data db.CookiePlatformRuntimeData) *orderapp.Plat
}
// GetOrder 委托订单详情查询。
func (r storeOrderRepository) GetOrder(ctx context.Context, orderID string) (*orderapp.Order, error) {
func (r OrderRepository) GetOrder(ctx context.Context, orderID string) (*orderapp.Order, error) {
// order 和 err 保存数据库订单查询结果及其错误。
order, err := r.store.Orders.Get(ctx, orderID)
if err != nil {
@@ -107,7 +107,7 @@ func (r storeOrderRepository) GetOrder(ctx context.Context, orderID string) (*or
}
// FindOrder 委托订单查询并把数据库的不存在错误转换为 exists=false。
func (r storeOrderRepository) FindOrder(ctx context.Context, orderID string) (*orderapp.Order, bool, error) {
func (r OrderRepository) 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) {
@@ -120,7 +120,7 @@ func (r storeOrderRepository) FindOrder(ctx context.Context, orderID string) (*o
}
// FindOrdersByIDs 委托数据库批量读取订单并转换为应用实体。
func (r storeOrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []string) (map[string]*orderapp.Order, error) {
func (r OrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []string) (map[string]*orderapp.Order, error) {
// orders、err 保存数据库批量订单及查询错误。
orders, err := r.store.Orders.FindByIDs(ctx, orderIDs)
if err != nil {
@@ -136,7 +136,7 @@ func (r storeOrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []st
}
// GetItem 委托商品信息查询。
func (r storeOrderRepository) GetItem(ctx context.Context, cookieID, itemID string) (*orderapp.ItemInfo, error) {
func (r OrderRepository) GetItem(ctx context.Context, cookieID, itemID string) (*orderapp.ItemInfo, error) {
// item 和 err 保存数据库商品查询结果及其错误。
item, err := r.store.Items.Get(ctx, cookieID, itemID)
if err != nil {
@@ -146,12 +146,12 @@ func (r storeOrderRepository) GetItem(ctx context.Context, cookieID, itemID stri
}
// SoftDeleteOrder 委托订单逻辑删除。
func (r storeOrderRepository) SoftDeleteOrder(ctx context.Context, orderID string) (bool, error) {
func (r OrderRepository) 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 {
func (r OrderRepository) WithTransaction(ctx context.Context, work func(orderapp.Writer) error) error {
// tx 和 err 保存事务创建结果。
tx, err := r.store.DB.BeginTx(ctx, nil)
if err != nil {
@@ -165,7 +165,7 @@ func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(ord
}
}()
// writer 是隐藏数据库事务细节的订单写入适配器。
writer := storeOrderWriter{store: r.store, tx: tx}
writer := orderWriter{store: r.store, tx: tx}
// err 保存事务工作函数的执行错误。
if err := work(writer); err != nil {
return err
@@ -178,8 +178,8 @@ func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(ord
return nil
}
// storeOrderWriter 将订单应用写入模型适配为数据库事务操作。
type storeOrderWriter struct {
// orderWriter 将订单应用写入模型适配为数据库事务操作。
type orderWriter struct {
// store 保存数据库 repository 聚合入口。
store *db.Store
// tx 保存当前事务,仅在基础设施适配器内部可见。
@@ -187,7 +187,7 @@ type storeOrderWriter struct {
}
// PatchOrder 委托事务内订单更新。
func (w storeOrderWriter) PatchOrder(ctx context.Context, orderID string, patch orderapp.OrderPatch) error {
func (w orderWriter) 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,
@@ -198,7 +198,7 @@ func (w storeOrderWriter) PatchOrder(ctx context.Context, orderID string, patch
}
// UpsertItemBasic 委托事务内商品基础信息写入。
func (w storeOrderWriter) UpsertItemBasic(ctx context.Context, item orderapp.ItemWrite) error {
func (w orderWriter) 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,
@@ -206,7 +206,7 @@ func (w storeOrderWriter) UpsertItemBasic(ctx context.Context, item orderapp.Ite
}
// UpsertOrder 委托事务内订单写入。
func (w storeOrderWriter) UpsertOrder(ctx context.Context, orderID string, options orderapp.UpsertOptions) error {
func (w orderWriter) 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,
@@ -218,7 +218,7 @@ func (w storeOrderWriter) UpsertOrder(ctx context.Context, orderID string, optio
}
// UpsertOrder 委托订单写入。
func (r storeOrderRepository) UpsertOrder(ctx context.Context, orderID string, opts orderapp.UpsertOptions) error {
func (r OrderRepository) 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,
@@ -230,7 +230,7 @@ func (r storeOrderRepository) UpsertOrder(ctx context.Context, orderID string, o
}
// BatchUpsertOrders 委托订单详情分片的单条多值 UPSERT。
func (r storeOrderRepository) BatchUpsertOrders(ctx context.Context, rows []orderapp.RefreshOrderWrite) error {
func (r OrderRepository) BatchUpsertOrders(ctx context.Context, rows []orderapp.RefreshOrderWrite) error {
if len(rows) == 0 {
return nil
}
@@ -265,12 +265,12 @@ func (r storeOrderRepository) BatchUpsertOrders(ctx context.Context, rows []orde
}
// LockCredentials 委托账号凭证锁。
func (r storeOrderRepository) LockCredentials(cookieID string) func() {
func (r OrderRepository) LockCredentials(cookieID string) func() {
return r.store.LockAccountCredentials(cookieID)
}
// LoadCookiePlatformDetail 委托平台凭证详情查询。
func (r storeOrderRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*orderapp.PlatformRuntimeData, error) {
func (r OrderRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*orderapp.PlatformRuntimeData, error) {
// data 和 err 保存平台运行视图查询结果。
data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if err != nil {
@@ -280,17 +280,17 @@ func (r storeOrderRepository) LoadCookiePlatformDetail(ctx context.Context, cook
}
// UpdateRenewalCookie 委托续期 Cookie 更新。
func (r storeOrderRepository) UpdateRenewalCookie(ctx context.Context, cookieID, value, metadata string, at int64) error {
func (r OrderRepository) 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) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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 {
@@ -300,7 +300,7 @@ func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cook
}
// Create 创建订单刷新后台任务并同步应用层模型默认值。
func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error {
func (r OrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error {
// dbJob 保存待写入的数据库任务模型。
dbJob := &db.OrderRefreshJob{
ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus,
@@ -316,7 +316,7 @@ func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJ
}
// Get 按用户读取订单刷新后台任务并转换为应用层模型。
func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) {
func (r OrderRepository) 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) {
@@ -329,22 +329,22 @@ func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string)
}
// Claim 原子抢占订单刷新后台任务。
func (r storeOrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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) {
func (r OrderRepository) 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 {
@@ -359,7 +359,7 @@ func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit
}
// RequeueExpired 将过期订单刷新后台任务恢复为 queued。
func (r storeOrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) {
func (r OrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) {
return r.store.OrderRefreshJobs.RequeueExpired(ctx, id, now)
}
@@ -376,24 +376,24 @@ func refreshJobFromDB(job *db.OrderRefreshJob) *orderapp.RefreshJob {
}
}
// newStoreOrderRepository 从完整 Store 构造订单应用服务窄 repository。
func newStoreOrderRepository(store *db.Store) *storeOrderRepository {
// NewOrderRepository 从数据库 Store 构造订单应用服务适配器。
func NewOrderRepository(store *db.Store) *OrderRepository {
if store == nil || store.Cookies == nil || store.Orders == nil || store.Items == nil {
return nil
}
return &storeOrderRepository{store: store}
return &OrderRepository{store: store}
}
// newStoreOrderRefreshJobRepository 构造订单刷新任务持久化适配器。
func newStoreOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository {
// NewOrderRefreshJobRepository 构造订单刷新任务持久化适配器。
func NewOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository {
if store == nil || store.OrderRefreshJobs == nil {
return nil
}
return storeOrderRepository{store: store}
return OrderRepository{store: store}
}
// 确保 Store 适配器始终覆盖订单应用服务所需的全部能力。
var _ orderapp.Repository = storeOrderRepository{}
var _ orderapp.UnitOfWork = storeOrderRepository{}
var _ orderapp.Writer = storeOrderWriter{}
var _ orderapp.RefreshJobRepository = storeOrderRepository{}
var _ orderapp.Repository = OrderRepository{}
var _ orderapp.UnitOfWork = OrderRepository{}
var _ orderapp.Writer = orderWriter{}
var _ orderapp.RefreshJobRepository = OrderRepository{}
+48
View File
@@ -0,0 +1,48 @@
package adapter
import (
"reflect"
"testing"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
// TestOrderRepositoryModelConversions 保证数据库订单模型转换为应用模型时不丢失业务字段。
func TestOrderRepositoryModelConversions(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"}
// expectedOrder 保存应用层应接收的订单实体。
expectedOrder := &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"}
// convertedOrder 保存适配器转换后的应用订单。
convertedOrder := orderFromDB(databaseOrder)
if !reflect.DeepEqual(convertedOrder, expectedOrder) {
t.Fatalf("订单转换结果不完整: got=%+v want=%+v", convertedOrder, expectedOrder)
}
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}
// expectedItem 保存应用层应接收的商品实体。
expectedItem := &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, expectedItem) {
t.Fatalf("商品转换结果不完整: got=%+v want=%+v", convertedItem, expectedItem)
}
if itemInfoFromDB(nil) != nil {
t.Fatal("空数据库商品应转换为空应用商品")
}
// databaseRuntime 保存模拟数据库读取的平台运行视图。
databaseRuntime := db.CookiePlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true}
// expectedRuntime 保存应用层应接收的平台运行视图。
expectedRuntime := &orderapp.PlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true}
// convertedRuntime 保存适配器转换后的平台运行视图。
convertedRuntime := platformRuntimeDataFromDB(databaseRuntime)
if !reflect.DeepEqual(convertedRuntime, expectedRuntime) {
t.Fatalf("平台运行视图转换结果不完整: got=%+v want=%+v", convertedRuntime, expectedRuntime)
}
}
+388
View File
@@ -0,0 +1,388 @@
package adapter
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// orderDetailMTop 是订单运行时需要的可选详情接口能力。
type orderDetailMTop interface {
// FetchOrderDetail 请求订单详情并返回平台响应中的订单字段。
FetchOrderDetail(context.Context, string, string) (*mtop.OrderDetailResult, error)
}
// OrderRuntimeHooks 定义 Server 运行时注入订单适配器的非持久化能力。
type OrderRuntimeHooks struct {
// Client 返回当前使用的平台客户端。
Client func() mtop.Client
// ClientAvailable 判断平台客户端是否已由 Server 显式装配。
ClientAvailable func() bool
// AccountRunning 判断账号运行实例是否在线。
AccountRunning func(string) bool
// AutomationReady 判断完整发货自动化依赖是否可用。
AutomationReady func() bool
// ManualFullDelivery 执行完整自动化发货;订单模型转换由装配回调负责。
ManualFullDelivery func(context.Context, *orderapp.Order) (int, error)
// UpdateRunningCookie 同步平台响应中的最新 Cookie 到账号运行实例。
UpdateRunningCookie func(context.Context, string, string)
// NotifyDelivery 发送手动发货结果通知。
NotifyDelivery func(string, string, string, string, string)
// RecoverExpiredSession 处理平台会话过期。
RecoverExpiredSession func(context.Context, string, error) bool
// ReportPersistenceFailure 记录本地订单状态写入失败。
ReportPersistenceFailure func(string, error)
}
// OrderRuntime 将订单应用 Port 适配到数据库凭证、MTOP 和账号运行时。
type OrderRuntime struct {
// store 提供订单确认发货所需的平台凭证读取和 Cookie 写回能力。
store *db.Store
// hooks 保存 Server 注入的运行时回调,不保存 HTTP 或 Server 对象。
hooks OrderRuntimeHooks
// reconciliation 保存外部动作成功后的补偿记录端口。
reconciliation orderapp.ReconciliationRecorder
// logger 记录不含凭证的订单持久化错误。
logger *slog.Logger
}
// NewOrderRuntime 构造订单平台与运行时适配器。
func NewOrderRuntime(store *db.Store, hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime {
// resolvedLogger 保存订单适配器使用的日志器。
resolvedLogger := logger
if resolvedLogger == nil {
resolvedLogger = slog.Default()
}
return &OrderRuntime{store: store, hooks: hooks, reconciliation: reconciliation, logger: resolvedLogger}
}
// AccountRunning 判断指定账号是否在线运行。
func (r *OrderRuntime) AccountRunning(cookieID string) bool {
return r != nil && r.hooks.AccountRunning != nil && r.hooks.AccountRunning(cookieID)
}
// AutomationReady 判断完整发货自动化依赖是否已装配。
func (r *OrderRuntime) AutomationReady() bool {
return r != nil && r.hooks.AutomationReady != nil && r.hooks.AutomationReady()
}
// ManualFullDelivery 执行完整自动化发货。
func (r *OrderRuntime) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) {
if r == nil || r.hooks.ManualFullDelivery == nil {
return 0, errors.New("自动化中心未初始化")
}
return r.hooks.ManualFullDelivery(ctx, order)
}
// MTopAvailable 判断平台客户端是否已由 Server 显式装配。
func (r *OrderRuntime) MTopAvailable() bool {
return r != nil && r.hooks.ClientAvailable != nil && r.hooks.ClientAvailable()
}
// mtopClient 返回订单流程使用的平台客户端。
func (r *OrderRuntime) mtopClient() mtop.Client {
if r == nil || r.hooks.Client == nil {
return nil
}
return r.hooks.Client()
}
// ConfirmShipment 使用当前账号凭证调用平台确认发货接口。
func (r *OrderRuntime) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult {
// success、messages、runtimeCookie、runtimeCookieChanged、callErr 保存确认发货结果及凭证变化。
success, messages, runtimeCookie, runtimeCookieChanged, callErr := r.consignWithCurrentCookie(ctx, cookieID, orderID, userID)
return orderapp.ConsignResult{Success: success, Messages: messages, RuntimeCookie: runtimeCookie, RuntimeCookieChanged: runtimeCookieChanged, Err: callErr}
}
// consignWithCurrentCookie 使用账号平台凭证确认发货并保存响应 Cookie。
func (r *OrderRuntime) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
if r == nil || r.store == nil || r.store.Cookies == nil {
return false, nil, "", false, errors.New("订单凭证存储未初始化")
}
// unlock 保护当前账号凭证读取和写回,保持现有订单流程的串行语义。
unlock := r.store.LockAccountCredentials(cookieID)
defer unlock()
// detail、loadErr 保存按账号读取的平台运行凭证及错误。
detail, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
if loadErr != nil {
return false, nil, "", false, loadErr
}
if detail.UserID != userID {
return false, nil, "", false, orderapp.ErrForbidden
}
if !hasStoredOrderCredential(detail) {
return false, nil, "", false, errors.New("账号 Cookie 为空")
}
// requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。
requestCtx, session := withOrderCookieSnapshot(ctx, detail)
// client 保存当前平台调用客户端。
client := r.mtopClient()
if client == nil {
return false, nil, "", false, errors.New("MTop 客户端未初始化")
}
// success、messages、updatedCookies、callErr 保存平台确认发货响应。
success, messages, updatedCookies, callErr := client.ConsignContext(requestCtx, detail.Value, orderID)
// value、valueChanged、handled、persistErr 保存响应 Cookie 会话写回结果。
value, valueChanged, handled, persistErr := r.persistOrderCookieSession(ctx, detail, session, updatedCookies)
if persistErr != nil {
// wrappedPersistErr 保存包含订单语义的 Cookie 写回错误。
wrappedPersistErr := fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr)
if callErr != nil {
return success, messages, "", false, errors.Join(callErr, wrappedPersistErr)
}
return success, messages, "", false, wrappedPersistErr
}
if handled {
// runtimeCookie 保存完整 Cookie 会话变化后的平面 Cookie 值。
runtimeCookie := ""
if valueChanged {
runtimeCookie = value
}
return success, messages, runtimeCookie, valueChanged, callErr
}
if callErr != nil {
return false, messages, "", false, callErr
}
if updatedCookies == "" || updatedCookies == detail.Value {
return success, messages, "", false, nil
}
// err 保存旧式平面 Cookie 写回错误。
if err := r.store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return success, messages, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err)
}
return success, messages, updatedCookies, true, nil
}
// UpdateRunningCookie 同步运行时账号 Cookie。
func (r *OrderRuntime) UpdateRunningCookie(ctx context.Context, cookieID, value string) {
if r != nil && r.hooks.UpdateRunningCookie != nil {
r.hooks.UpdateRunningCookie(ctx, cookieID, value)
}
}
// NotifyDelivery 发送发货结果通知。
func (r *OrderRuntime) NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
if r != nil && r.hooks.NotifyDelivery != nil {
r.hooks.NotifyDelivery(cookieID, buyerID, itemID, chatID, message)
}
}
// RecordOrderReconciliation 创建外部动作成功后的补偿记录。
func (r *OrderRuntime) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
if r == nil || r.reconciliation == nil {
return "", errors.New("订单补偿存储未初始化")
}
return r.reconciliation.RecordReconciliation(ctx, orderID, cookieID, kind, message)
}
// RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。
func (r *OrderRuntime) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) {
return r.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message)
}
// ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。
func (r *OrderRuntime) ReportPersistenceFailure(orderID string, err error) {
if r == nil || err == nil {
return
}
r.logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err)
if r.hooks.ReportPersistenceFailure != nil {
r.hooks.ReportPersistenceFailure(orderID, err)
}
}
// RecoverExpiredSession 处理订单刷新应用服务报告的平台会话过期。
func (r *OrderRuntime) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool {
return r != nil && r.hooks.RecoverExpiredSession != nil && r.hooks.RecoverExpiredSession(ctx, cookieID, err)
}
// DetailAvailable 判断平台详情接口是否可用。
func (r *OrderRuntime) DetailAvailable() bool {
// client 保存当前平台客户端。
client := r.mtopClient()
// _, available 丢弃客户端具体类型并记录详情接口能力。
_, available := client.(orderDetailMTop)
return available
}
// SoldAvailable 判断平台已售订单列表接口是否可用。
func (r *OrderRuntime) SoldAvailable() bool {
// client 保存当前平台客户端。
client := r.mtopClient()
// _, available 丢弃客户端具体类型并记录订单列表接口能力。
_, available := client.(mtop.SoldOrderFetcher)
return available
}
// CredentialAvailable 判断平台请求视图是否包含可用 Cookie。
func (r *OrderRuntime) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool {
return detail != nil && strings.TrimSpace(detail.Value) != ""
}
// FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。
func (r *OrderRuntime) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) {
// fetcher、available 保存详情接口实现及其可用状态。
fetcher, available := r.mtopClient().(orderDetailMTop)
if !available {
return orderapp.RefreshDetailFetchResult{}, orderapp.ErrRefreshDetailUnsupported
}
if detail == nil {
return orderapp.RefreshDetailFetchResult{}, errors.New("订单详情请求缺少账号凭证")
}
// requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。
requestCtx, session := withOrderCookieSnapshot(ctx, platformRuntimeDataForOrder(detail))
// result、callErr 保存平台详情响应和错误。
result, callErr := fetcher.FetchOrderDetail(requestCtx, detail.Value, orderID)
// cookieUpdate 保存平台详情请求观察到的 Cookie 会话变化。
cookieUpdate := orderCookieUpdate(detail, session)
if callErr != nil {
return orderapp.RefreshDetailFetchResult{CookieUpdate: cookieUpdate}, callErr
}
if result == nil {
return orderapp.RefreshDetailFetchResult{CookieUpdate: cookieUpdate}, 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: cookieUpdate}, nil
}
// FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。
func (r *OrderRuntime) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) {
// fetcher、available 保存订单列表接口实现及其可用状态。
fetcher, available := r.mtopClient().(mtop.SoldOrderFetcher)
if !available {
return orderapp.RefreshSoldFetchResult{}, errors.New("当前 MTop 客户端不支持订单列表发现")
}
if detail == nil {
return orderapp.RefreshSoldFetchResult{}, errors.New("订单列表请求缺少账号凭证")
}
// requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。
requestCtx, session := withOrderCookieSnapshot(ctx, platformRuntimeDataForOrder(detail))
// orders 保存跨分页累积的平台订单。
orders := make([]orderapp.RefreshSoldOrder, 0)
// pageNumber 是当前请求的订单列表页码。
for pageNumber := 1; pageNumber <= orderRuntimeMaxSoldOrderPages; pageNumber++ {
// page、callErr 保存当前订单列表页及错误。
page, callErr := fetcher.FetchSoldOrdersPage(requestCtx, detail.Value, pageNumber, 30)
if callErr != nil {
return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: orderCookieUpdate(detail, session)}, callErr
}
if page == nil {
return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: orderCookieUpdate(detail, session)}, errors.New("订单列表接口未返回结果")
}
// 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: orderCookieUpdate(detail, session)}, nil
}
// PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。
func (r *OrderRuntime) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) {
if detail == nil || !update.Handled {
return "", false, false, nil
}
if !update.Changed {
return detail.Value, false, true, nil
}
if r == nil || r.store == nil || r.store.Cookies == nil {
return update.Value, update.Value != detail.Value, true, errors.New("账号 Cookie 持久化服务未初始化")
}
// persistErr 保存账号续期 Cookie 写入错误。
persistErr := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, update.Value, update.MetadataJSON, time.Now().Unix())
if persistErr != nil {
return update.Value, update.Value != detail.Value, true, persistErr
}
return update.Value, update.Value != detail.Value, true, nil
}
// IsSessionExpired 判断平台错误是否为会话过期。
func (r *OrderRuntime) IsSessionExpired(err error) bool {
return mtop.IsSessionExpiredErr(err)
}
// withOrderCookieSnapshot 为订单平台请求挂载平面 Cookie 或完整 Cookie Jar。
func withOrderCookieSnapshot(ctx context.Context, detail db.CookiePlatformRuntimeData) (context.Context, *mtop.CookieSession) {
// snapshot、complete 保存账号 metadata 中的 Cookie Jar 及其完整性。
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !complete {
return mtop.WithFlatCookieSession(ctx, detail.Value)
}
return mtop.WithCookieSnapshot(ctx, snapshot)
}
// hasStoredOrderCredential 判断订单平台视图是否包含可用凭证。
func hasStoredOrderCredential(detail db.CookiePlatformRuntimeData) bool {
if strings.TrimSpace(detail.Value) != "" {
return true
}
// _, complete 丢弃 Cookie 快照内容,仅判断是否存在完整凭证。
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
// platformRuntimeDataForOrder 将应用平台运行视图转换为数据库适配内部模型。
func platformRuntimeDataForOrder(data *orderapp.PlatformRuntimeData) db.CookiePlatformRuntimeData {
if data == nil {
return db.CookiePlatformRuntimeData{}
}
return db.CookiePlatformRuntimeData{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}
}
// orderCookieUpdate 将 MTOP 会话状态转换为订单应用层 Cookie 更新模型。
func orderCookieUpdate(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}
}
// persistOrderCookieSession 保存确认发货响应中的完整或平面 Cookie 会话。
func (r *OrderRuntime) persistOrderCookieSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession, updatedCookies string) (string, bool, bool, error) {
// value、snapshot、changed 保存平台 CookieSession 状态。
value, snapshot, changed := session.State()
if !changed {
if snapshot != nil {
return detail.Value, false, true, nil
}
return "", false, false, nil
}
// metadata 保存移除或更新 Cookie 快照后的账号元数据。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if r.store == nil || r.store.Cookies == nil {
return value, value != detail.Value, true, errors.New("账号 Cookie 持久化 repository 未初始化")
}
// persistErr 保存完整 Cookie 会话写回错误。
persistErr := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
if persistErr != nil {
return value, value != detail.Value, true, persistErr
}
return value, value != detail.Value, true, nil
}
// orderRuntimeMaxSoldOrderPages 限制一次订单发现最多请求的平台页数。
const orderRuntimeMaxSoldOrderPages = 100
// 确保订单运行时覆盖手动发货和订单刷新应用层端口。
var _ orderapp.ManualShipRuntime = (*OrderRuntime)(nil)
var _ orderapp.RefreshRuntime = (*OrderRuntime)(nil)
+137
View File
@@ -0,0 +1,137 @@
package adapter
import (
"context"
"errors"
"testing"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/xianyu/mtop"
)
// orderRuntimeMTopFake 是订单运行时测试使用的平台客户端替身。
type orderRuntimeMTopFake struct {
// consign 保存确认发货调用结果函数。
consign func(context.Context, string, string) (bool, []string, string, error)
// consignCalls 记录确认发货调用次数。
consignCalls int
}
// FetchUserProfile 满足基础 MTOP 客户端接口但不参与订单测试。
func (f *orderRuntimeMTopFake) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, errors.New("订单测试未预期资料请求")
}
// ConsignContext 返回测试预置的确认发货结果。
func (f *orderRuntimeMTopFake) ConsignContext(ctx context.Context, cookies, orderID string) (bool, []string, string, error) {
f.consignCalls++
if f.consign == nil {
return false, nil, "", errors.New("订单测试未配置确认发货结果")
}
return f.consign(ctx, cookies, orderID)
}
// FetchItemsPage 满足基础 MTOP 客户端接口但不参与订单测试。
func (f *orderRuntimeMTopFake) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, errors.New("订单测试未预期商品分页请求")
}
// FetchAllItems 满足基础 MTOP 客户端接口但不参与订单测试。
func (f *orderRuntimeMTopFake) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, errors.New("订单测试未预期商品列表请求")
}
// PublishItem 满足基础 MTOP 客户端接口但不参与订单测试。
func (f *orderRuntimeMTopFake) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, errors.New("订单测试未预期商品发布请求")
}
// RefreshTokenWithDeviceIDContext 满足基础 MTOP 客户端接口但不参与订单测试。
func (f *orderRuntimeMTopFake) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
return nil, errors.New("订单测试未预期令牌请求")
}
// TestOrderRuntimeConfirmShipmentPersistsCookie 验证确认发货成功会写回平台返回的新 Cookie。
func TestOrderRuntimeConfirmShipmentPersistsCookie(t *testing.T) {
// store、cleanup 保存测试数据库和资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// client 保存返回成功及新 Cookie 的平台客户端替身。
client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) {
return true, []string{"SUCCESS"}, "sid=new", nil
}}
// runtime 保存绑定数据库和平台客户端的订单运行时适配器。
runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil)
// result 保存确认发货的应用层结果。
result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 1)
if !result.Success || result.Err != nil || result.RuntimeCookie != "sid=new" || !result.RuntimeCookieChanged {
t.Fatalf("确认发货结果异常: %+v", result)
}
// savedCookie 保存凭证适配器写回数据库的 Cookie。
savedCookie, savedErr := store.Cookies.GetValue(context.Background(), "cid")
if savedErr != nil || savedCookie != "sid=new" {
t.Fatalf("Cookie 写回异常: value=%q err=%v", savedCookie, savedErr)
}
}
// TestOrderRuntimeConfirmShipmentPropagatesPlatformError 验证平台错误会透传且不会伪造成功。
func TestOrderRuntimeConfirmShipmentPropagatesPlatformError(t *testing.T) {
// store、cleanup 保存测试数据库和资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// expectedErr 保存平台确认发货错误。
expectedErr := errors.New("平台确认发货失败")
// client 保存返回平台错误的客户端替身。
client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) {
return false, []string{"FAIL"}, "", expectedErr
}}
// runtime 保存订单运行时适配器。
runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil)
// result 保存平台错误对应的应用层结果。
result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 1)
if result.Success || !errors.Is(result.Err, expectedErr) || client.consignCalls != 1 {
t.Fatalf("平台错误未正确透传: result=%+v calls=%d", result, client.consignCalls)
}
}
// TestOrderRuntimeConfirmShipmentRejectsOtherOwner 验证跨用户确认发货会在平台调用前拒绝。
func TestOrderRuntimeConfirmShipmentRejectsOtherOwner(t *testing.T) {
// store、cleanup 保存测试数据库和资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// client 保存用于确认平台未被调用的客户端替身。
client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) {
return true, nil, "sid=unexpected", nil
}}
// runtime 保存订单运行时适配器。
runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil)
// result 保存跨用户请求的应用层结果。
result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 999)
if !errors.Is(result.Err, orderapp.ErrForbidden) || client.consignCalls != 0 {
t.Fatalf("跨用户请求未被拒绝: result=%+v calls=%d", result, client.consignCalls)
}
}
// TestOrderRuntimeConfirmShipmentHonorsCancellation 验证请求取消会传入平台调用并返回取消错误。
func TestOrderRuntimeConfirmShipmentHonorsCancellation(t *testing.T) {
// store、cleanup 保存测试数据库和资源清理函数。
store, cleanup := newAdapterTestStore(t)
defer cleanup()
// client 保存检查 Context 取消状态的客户端替身。
client := &orderRuntimeMTopFake{consign: func(ctx context.Context, _, _ string) (bool, []string, string, error) {
return false, nil, "", ctx.Err()
}}
// runtime 保存订单运行时适配器。
runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil)
// ctx 保存已经取消的订单请求上下文。
ctx, cancel := context.WithCancel(context.Background())
cancel()
// result 保存取消请求对应的应用层结果。
result := runtime.ConfirmShipment(ctx, "cid", "order-1", 1)
if !errors.Is(result.Err, context.Canceled) {
t.Fatalf("取消错误未透传: %+v", result)
}
}
// 确保测试平台替身覆盖订单运行时依赖的基础客户端接口。
var _ mtop.Client = (*orderRuntimeMTopFake)(nil)
+216
View File
@@ -0,0 +1,216 @@
package adapter
import (
"context"
"errors"
"log/slog"
"xianyu-go/internal/account"
accountapp "xianyu-go/internal/application/account"
adminapp "xianyu-go/internal/application/admin"
chatapp "xianyu-go/internal/application/chat"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
domainchat "xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/reconciliation"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/qrlogin"
xrenew "xianyu-go/internal/xianyu/renew"
)
// MTOPClient 是 Server 装配平台适配器时使用的客户端别名;HTTP 层不直接导入 MTOP 实现包。
type MTOPClient = mtop.Client
// QRLoginService 定义 HTTP 扫码端点所需的最小二维码会话协议。
type QRLoginService interface {
// GenerateQRCode 创建一次待轮询的二维码会话并返回会话标识和二维码地址。
GenerateQRCode(context.Context) (string, string, error)
// GetSessionStatus 返回会话当前状态;返回值仅在 HTTP 适配器边界做兼容字段转换。
GetSessionStatus(string) map[string]any
// CompleteVerification 完成风控验证并返回本次请求作用域内的凭证值。
CompleteVerification(context.Context, string) (string, string, error)
}
// Dependencies 封装 Server 装配所需的基础设施;底层 Store 仅在 adapter 内部可见。
type Dependencies struct {
// store 保存所有数据库适配器共享的持久化入口,绝不向 HTTP 层公开。
store *db.Store
}
// NewDependencies 构造 Server 使用的基础设施工厂并校验数据库 Store。
func NewDependencies(store *db.Store) (*Dependencies, error) {
if store == nil {
return nil, errors.New("server 基础设施 Store 不能为空")
}
return &Dependencies{store: store}, nil
}
// NewMTOPClient 创建默认平台客户端,供生产构造与测试替换使用。
func NewMTOPClient() MTOPClient {
return mtop.NewClient()
}
// NewQRLoginService 创建默认二维码会话服务。
func NewQRLoginService(logger *slog.Logger) QRLoginService {
return qrlogin.NewManager(logger)
}
// NewLongLoginClient 创建默认长登录平台客户端。
func NewLongLoginClient() LongLoginClient {
return xrenew.Service{}
}
// NewOrderRepository 返回订单读写应用服务共用的数据库适配器。
func (d *Dependencies) NewOrderRepository() *OrderRepository { return NewOrderRepository(d.store) }
// NewOrderReconciliationRepository 返回订单补偿记录的持久化适配器。
func (d *Dependencies) NewOrderReconciliationRepository() *OrderReconciliationRepository {
return NewOrderReconciliationRepository(d.store)
}
// NewOrderRuntime 返回订单运行时适配器,Server 只提供运行时回调而不访问持久化入口。
func (d *Dependencies) NewOrderRuntime(hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime {
return NewOrderRuntime(d.store, hooks, reconciliation, logger)
}
// NewOrderRefreshJobRepository 返回订单刷新任务的持久化适配器。
func (d *Dependencies) NewOrderRefreshJobRepository() orderapp.RefreshJobRepository {
return NewOrderRefreshJobRepository(d.store)
}
// NewAccountLoginRepository 返回账号凭证和摘要适配器。
func (d *Dependencies) NewAccountLoginRepository() *AccountLoginRepository {
return NewAccountLoginRepository(d.store)
}
// NewAccountSettingsRepository 返回账号设置写入适配器。
func (d *Dependencies) NewAccountSettingsRepository() *AccountSettingsRepository {
return NewAccountSettingsRepository(d.store)
}
// NewAccountSummaryRepository 返回账号非敏感摘要适配器。
func (d *Dependencies) NewAccountSummaryRepository() *AccountSummaryRepository {
return NewAccountSummaryRepository(d.store)
}
// NewAutomationCredentialWakeRepository 返回凭证恢复后的自动化任务唤醒适配器。
func (d *Dependencies) NewAutomationCredentialWakeRepository() *AutomationCredentialWakeRepository {
return NewAutomationCredentialWakeRepository(d.store)
}
// NewItemBatchRepository 返回商品批量发布状态适配器。
func (d *Dependencies) NewItemBatchRepository() *ItemBatchRepository {
return NewItemBatchRepository(d.store)
}
// NewItemBatchPreviewPort 返回批量预检所需的归属与本地文件适配器。
func (d *Dependencies) NewItemBatchPreviewPort() *ItemBatchPreviewPort {
return NewItemBatchPreviewPort(d.store)
}
// NewItemBatchPublishPort 返回批量逐行远端发布适配器。
func (d *Dependencies) NewItemBatchPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error), readFile ReadPublishImageFile, download DownloadPublishImageURL) *ItemBatchPublishPort {
return NewItemBatchPublishPort(d.store, client, logger, update, recover, readFile, download)
}
// NewItemPublishPort 返回单商品发布和类目推荐共用的平台适配器。
func (d *Dependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort {
return NewItemPublishPort(d.store, client, logger, update, recover)
}
// NewItemPublishRepository 返回单商品发布后的本地持久化适配器。
func (d *Dependencies) NewItemPublishRepository() *ItemPublishRepository {
return NewItemPublishRepository(d.store)
}
// NewItemCatalogRepository 返回商品目录读写适配器。
func (d *Dependencies) NewItemCatalogRepository() *ItemCatalogRepository {
return NewItemCatalogRepository(d.store)
}
// NewItemSyncRepository 返回商品同步适配器。
func (d *Dependencies) NewItemSyncRepository(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemSyncRepository {
return NewItemSyncRepository(d.store, client, logger, update, recover)
}
// NewQRLoginRepository 返回扫码登录持久化适配器。
func (d *Dependencies) NewQRLoginRepository() accountapp.QRLoginRepository {
return NewQRLoginRepository(d.store)
}
// NewAutomationRepository 返回自动化规则、异常和发布规则共用适配器。
func (d *Dependencies) NewAutomationRepository() *AutomationRepository {
return NewAutomationRepository(d.store)
}
// NewSettingsRepository 返回系统设置适配器。
func (d *Dependencies) NewSettingsRepository() *SettingsRepository {
return NewSettingsRepository(d.store)
}
// NewAuthenticationRepository 返回用户认证持久化适配器。
func (d *Dependencies) NewAuthenticationRepository() *AuthenticationRepository {
return NewAuthenticationRepository(d.store)
}
// NewAccountLoginAuditRepository 返回登录审计持久化适配器。
func (d *Dependencies) NewAccountLoginAuditRepository() *AccountLoginAuditRepository {
return NewAccountLoginAuditRepository(d.store)
}
// NewAccountTaskRepository 返回账号自动化任务适配器。
func (d *Dependencies) NewAccountTaskRepository() *AccountTaskRepository {
return NewAccountTaskRepository(d.store)
}
// NewAdminRepository 返回管理员用户与统计适配器。
func (d *Dependencies) NewAdminRepository() adminapp.Repository {
return NewAdminRepository(d.store)
}
// NewChatSendingApplication 装配聊天应用服务,聊天持久化 Store 不泄露给 HTTP 层。
func (d *Dependencies) NewChatSendingApplication(service *domainchat.Service, manager *account.Manager, client func() MTOPClient) *chatapp.Service {
return NewChatSendingApplication(service, d.store, manager, client)
}
// NewNotificationUncertainRepository 返回通知不确定态查询适配器。
func (d *Dependencies) NewNotificationUncertainRepository() notificationsapp.Repository {
return NewNotificationUncertainRepository(d.store)
}
// NewNotificationChannelRepository 返回通知渠道和账号绑定适配器。
func (d *Dependencies) NewNotificationChannelRepository() notificationsapp.ChannelRepository {
return NewNotificationChannelRepository(d.store)
}
// NewAnalyticsRepository 返回订单分析只读适配器。
func (d *Dependencies) NewAnalyticsRepository() *AnalyticsRepository {
return NewAnalyticsRepository(d.store)
}
// NewCardsRepository 返回卡券库存适配器。
func (d *Dependencies) NewCardsRepository() *CardsRepository { return NewCardsRepository(d.store) }
// NewDefaultReplyRepository 返回默认回复适配器。
func (d *Dependencies) NewDefaultReplyRepository() *DefaultReplyRepository {
return NewDefaultReplyRepository(d.store)
}
// NewKeywordRepository 返回关键词和指定商品回复适配器。
func (d *Dependencies) NewKeywordRepository() *KeywordRepository {
return NewKeywordRepository(d.store)
}
// NewTransactionRepository 返回应用事务执行适配器。
func (d *Dependencies) NewTransactionRepository() *TransactionRepository {
return NewTransactionRepository(d.store)
}
// NewDatabaseHealth 返回数据库健康检查适配器。
func (d *Dependencies) NewDatabaseHealth() *DatabaseHealth { return NewDatabaseHealth(d.store) }
// NewReconciliationService 返回订单补偿扫描服务;它仅由 Server 生命周期调用。
func (d *Dependencies) NewReconciliationService(logger *slog.Logger) *reconciliation.Service {
return reconciliation.New(d.store, logger)
}
+247
View File
@@ -0,0 +1,247 @@
package adapter
import (
"context"
"errors"
"strings"
settingsapp "xianyu-go/internal/application/settings"
"xianyu-go/internal/db"
)
// SettingsRepository 将系统、用户和账号 AI 设置数据库模型适配为应用层 Port。
type SettingsRepository struct {
// store 保存数据库聚合入口,仅由适配器访问数据库模型。
store *db.Store
}
// NewSettingsRepository 构造设置数据库适配器。
func NewSettingsRepository(store *db.Store) *SettingsRepository {
// repository 保存设置用例所需的数据库入口。
repository := &SettingsRepository{store: store}
return repository
}
// IsSensitiveSettingKey 判断设置键是否属于数据库维护的敏感白名单。
func (r *SettingsRepository) IsSensitiveSettingKey(key string) bool {
if r == nil {
return false
}
return db.IsSensitiveSettingKey(key)
}
// SensitiveSettingKeys 返回敏感设置键名,不返回任何敏感值。
func (r *SettingsRepository) SensitiveSettingKeys() []string {
if r == nil {
return nil
}
return db.SensitiveSettingKeys()
}
// PublicSystem 读取公开系统设置。
func (r *SettingsRepository) PublicSystem(ctx context.Context) (map[string]string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return nil, err
}
return r.store.Settings.Public(ctx)
}
// RedactedSystem 读取已脱敏系统设置,敏感值只转换为 configured 标记。
func (r *SettingsRepository) RedactedSystem(ctx context.Context) (map[string]string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return nil, err
}
return r.store.Settings.Redacted(ctx)
}
// GetSystem 读取一项系统设置,仅供应用层受控业务使用。
func (r *SettingsRepository) GetSystem(ctx context.Context, key string) (string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return "", err
}
return r.store.Settings.Get(ctx, key)
}
// ReadSensitiveSystem 通过数据库现有 fail-closed 审计入口读取系统秘密。
func (r *SettingsRepository) ReadSensitiveSystem(ctx context.Context, userID int64, key, action, resource string) (string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return "", err
}
return r.store.ReadSensitiveSetting(ctx, userID, key, action, resource)
}
// ApplySystemChanges 将应用层敏感变更命令转换为数据库模型并原子保存。
func (r *SettingsRepository) ApplySystemChanges(ctx context.Context, values map[string]string, secrets map[string]settingsapp.SecretChange) error {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return err
}
// dbSecrets 保存转换后的数据库敏感设置命令。
dbSecrets := make(map[string]db.SensitiveSettingChange, len(secrets))
// key 是敏感设置键名;change 是应用层三态命令。
for key, change := range secrets {
dbSecrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value}
}
return r.store.Settings.ApplyChanges(ctx, values, dbSecrets)
}
// SetSystem 保存一项普通系统设置。
func (r *SettingsRepository) SetSystem(ctx context.Context, key, value string) error {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return err
}
return r.store.Settings.Set(ctx, key, value)
}
// AddAudit 将应用层非敏感审计模型转换为数据库记录。
func (r *SettingsRepository) AddAudit(ctx context.Context, record settingsapp.AuditRecord) error {
// err 表示审计存储未装配。
if err := r.validateAudit(); err != nil {
return err
}
return r.store.SecurityAudit.Add(ctx, db.SecurityAuditLog{
UserID: record.UserID, Action: record.Action, Resource: record.Resource,
Keys: record.Keys, Outcome: record.Outcome,
})
}
// ListUser 读取指定用户的全部偏好设置。
func (r *SettingsRepository) ListUser(ctx context.Context, userID int64) (map[string]string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return nil, err
}
return r.store.UserSettings.AllForUser(ctx, userID)
}
// GetUser 读取指定用户的一项偏好设置。
func (r *SettingsRepository) GetUser(ctx context.Context, userID int64, key string) (string, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return "", err
}
return r.store.UserSettings.GetForUser(ctx, userID, key)
}
// SetUser 保存指定用户的一项偏好设置。
func (r *SettingsRepository) SetUser(ctx context.Context, userID int64, key, value string) error {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return err
}
return r.store.UserSettings.SetForUser(ctx, userID, key, value)
}
// CheckOwnership 查询账号所属用户,不读取或解密任何账号凭证。
func (r *SettingsRepository) CheckOwnership(ctx context.Context, userID int64, cookieID string) (int64, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return 0, err
}
// owned、err 保存非敏感账号归属结果及查询错误。
owned, err := r.store.Cookies.ExistsOwned(ctx, userID, strings.TrimSpace(cookieID))
if err != nil {
return 0, err
}
if owned {
return userID, nil
}
// ownerID、err 保存跨用户账号所有者标识及查询错误。
ownerID, err := r.store.Cookies.GetOwnerID(ctx, strings.TrimSpace(cookieID))
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return 0, settingsapp.ErrAccountNotFound
}
return 0, err
}
return ownerID, nil
}
// ListAIReply 查询用户范围内的账号 AI 设置摘要,数据库层不会读取 API 密钥。
func (r *SettingsRepository) ListAIReply(ctx context.Context, userID int64) ([]settingsapp.AIReplySettings, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return nil, err
}
// records、err 保存数据库 AI 设置摘要及查询错误。
records, err := r.store.AIReply.ListForUser(ctx, userID)
if err != nil {
return nil, err
}
// result 保存转换后的应用 AI 设置摘要。
result := make([]settingsapp.AIReplySettings, 0, len(records))
// record 是当前待转换的数据库 AI 设置摘要。
for _, record := range records {
result = append(result, aiReplyModel(record))
}
return result, nil
}
// GetAIReply 从用户范围摘要中读取单个账号,避免解密或传递账号 API 密钥。
func (r *SettingsRepository) GetAIReply(ctx context.Context, userID int64, cookieID string) (settingsapp.AIReplySettings, error) {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return settingsapp.AIReplySettings{}, err
}
// records、err 保存数据库 AI 设置摘要及查询错误。
records, err := r.store.AIReply.ListForUser(ctx, userID)
if err != nil {
return settingsapp.AIReplySettings{}, err
}
// record 是当前待匹配的账号 AI 设置摘要。
for _, record := range records {
if record.CookieID == cookieID {
return aiReplyModel(record), nil
}
}
return settingsapp.AIReplySettings{}, settingsapp.ErrConfigNotFound
}
// UpsertAIReply 将账号 AI 设置转换为数据库模型并保存。
func (r *SettingsRepository) UpsertAIReply(ctx context.Context, cookieID string, settings settingsapp.AIReplySettings) error {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return err
}
return r.store.AIReply.UpsertSettings(ctx, cookieID, db.AIReplySettings{
CookieID: cookieID, AIEnabled: settings.AIEnabled,
MaxDiscountPercent: settings.MaxDiscountPercent, MaxDiscountAmount: settings.MaxDiscountAmount,
MaxBargainRounds: settings.MaxBargainRounds, CustomPrompts: settings.CustomPrompts,
})
}
// validate 检查设置适配器及其数据库子仓储是否完整装配。
func (r *SettingsRepository) validate() error {
if r == nil || r.store == nil || r.store.Settings == nil || r.store.UserSettings == nil || r.store.AIReply == nil || r.store.Cookies == nil {
return errors.New("设置数据库适配器未初始化")
}
return nil
}
// validateAudit 检查敏感设置审计所需的独立存储,避免普通设置被无关依赖阻断。
func (r *SettingsRepository) validateAudit() error {
// err 表示设置数据库适配器未装配。
if err := r.validate(); err != nil {
return err
}
if r.store.SecurityAudit == nil {
return errors.New("敏感访问审计未初始化")
}
return nil
}
// aiReplyModel 将不含 API 密钥的数据库摘要转换为应用模型。
func aiReplyModel(record db.AIReplySettings) settingsapp.AIReplySettings {
return settingsapp.AIReplySettings{
CookieID: record.CookieID, AIEnabled: record.AIEnabled,
MaxDiscountPercent: record.MaxDiscountPercent, MaxDiscountAmount: record.MaxDiscountAmount,
MaxBargainRounds: record.MaxBargainRounds, CustomPrompts: record.CustomPrompts,
}
}
var _ settingsapp.Repository = (*SettingsRepository)(nil)
+52
View File
@@ -0,0 +1,52 @@
package adapter
import (
"context"
"database/sql"
"errors"
"xianyu-go/internal/db"
)
// TransactionRepository 将数据库事务生命周期适配为 Server 的最小执行端口。
type TransactionRepository struct {
// store 保存数据库聚合入口,仅在事务适配器内部使用。
store *db.Store
}
// NewTransactionRepository 创建数据库事务适配器。
func NewTransactionRepository(store *db.Store) *TransactionRepository {
return &TransactionRepository{store: store}
}
// WithTransaction 创建、提交或回滚一个数据库事务。
func (repository *TransactionRepository) WithTransaction(ctx context.Context, work func(*sql.Tx) error) error {
if repository == nil || repository.store == nil || repository.store.DB == nil {
return errors.New("事务 repository 未初始化")
}
if work == nil {
return errors.New("事务工作函数不能为空")
}
// tx 和 beginErr 保存事务创建结果及错误。
tx, beginErr := repository.store.DB.BeginTx(ctx, nil)
if beginErr != nil {
return beginErr
}
// committed 标识事务是否已经提交,避免提交失败后重复处理回滚。
committed := false
defer func() {
if !committed {
_ = tx.Rollback()
}
}()
// workErr 保存事务工作函数返回的业务错误。
if workErr := work(tx); workErr != nil {
return workErr
}
// commitErr 保存事务提交错误。
if commitErr := tx.Commit(); commitErr != nil {
return commitErr
}
committed = true
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package adapter
import (
"context"
"database/sql"
"testing"
"xianyu-go/internal/db"
)
// TestTransactionRepositoryRejectsMissingDependencies 验证事务适配器缺少数据库或工作函数时快速失败。
func TestTransactionRepositoryRejectsMissingDependencies(t *testing.T) {
// repository 保存缺少数据库的事务适配器。
repository := NewTransactionRepository(nil)
// err 保存缺少数据库时的错误。
if err := repository.WithTransaction(context.Background(), func(*sql.Tx) error { return nil }); err == nil {
t.Fatal("缺少数据库时事务不应伪装成功")
}
// err 保存缺少数据库和工作函数时的错误。
if err := NewTransactionRepository(nil).WithTransaction(context.Background(), nil); err == nil {
t.Fatal("缺少数据库和工作函数时事务不应伪装成功")
}
// database、dialect 和 openErr 保存最小 SQLite 数据库装配结果。
database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/transaction.db")
if openErr != nil {
t.Fatalf("打开测试数据库失败: %v", openErr)
}
defer database.Close()
// err 保存有效数据库但缺少工作函数时的错误。
if err := NewTransactionRepository(db.NewStore(database, dialect)).WithTransaction(context.Background(), nil); err == nil {
t.Fatal("缺少事务工作函数时不应伪装成功")
}
}
@@ -0,0 +1,123 @@
package account
import (
"context"
"errors"
)
// ErrPasswordMismatch 表示当前密码未通过校验,调用方应返回认证失败而不是基础设施错误。
var ErrPasswordMismatch = errors.New("密码错误")
// ErrUsernameTaken 表示新的用户名已经被其他用户占用。
var ErrUsernameTaken = errors.New("用户名已存在")
// AuthUser 是认证用例返回的非敏感用户身份,不包含密码哈希或邮箱等持久化字段。
type AuthUser struct {
// ID 是本地用户的稳定身份标识,用于创建会话和归属校验。
ID int64
// Username 是登录用户名和会话展示名称。
Username string
// IsAdmin 表示用户是否拥有管理员权限。
IsAdmin bool
}
// AuthenticationRepository 定义认证用例需要的最小用户与会话端口。
type AuthenticationRepository interface {
// IsSystemInitialized 判断系统是否已经存在管理员账号。
IsSystemInitialized(context.Context) (bool, error)
// InitializeAdmin 创建或重置管理员账号,并返回本次是否新建。
InitializeAdmin(context.Context, string, string) (bool, error)
// UsernameByEmail 按邮箱取得登录用户名,不向应用层返回完整用户记录。
UsernameByEmail(context.Context, string) (string, error)
// VerifyPassword 校验用户密码并返回非敏感身份;密码错误返回 ErrPasswordMismatch 或 ok=false。
VerifyPassword(context.Context, string, string) (AuthUser, bool, error)
// UpdatePassword 更新指定用户名的密码并撤销旧会话。
UpdatePassword(context.Context, string, string) (bool, error)
// UpdateCredentials 原子更新用户名及可选密码,并撤销旧会话。
UpdateCredentials(context.Context, int64, string, string) error
// CreateSession 为已经通过密码校验的用户创建会话。
CreateSession(context.Context, AuthUser) (string, error)
}
// AuthenticationService 编排登录、初始化、密码修改和登录凭据更新,不依赖 HTTP 或数据库模型。
type AuthenticationService struct {
// repository 提供用户密码与会话的窄持久化能力。
repository AuthenticationRepository
}
// NewAuthenticationService 构造认证应用服务并校验必需的持久化端口。
func NewAuthenticationService(repository AuthenticationRepository) (*AuthenticationService, error) {
if repository == nil {
return nil, errors.New("认证 repository 未初始化")
}
return &AuthenticationService{repository: repository}, nil
}
// IsSystemInitialized 返回系统是否已完成管理员初始化。
func (s *AuthenticationService) IsSystemInitialized(ctx context.Context) (bool, error) {
if s == nil || s.repository == nil {
return false, errors.New("认证服务未初始化")
}
return s.repository.IsSystemInitialized(ctx)
}
// InitializeAdmin 创建或重置管理员账号;初始化并发控制由 HTTP 层保留。
func (s *AuthenticationService) InitializeAdmin(ctx context.Context, email, password string) (bool, error) {
if s == nil || s.repository == nil {
return false, errors.New("认证服务未初始化")
}
return s.repository.InitializeAdmin(ctx, email, password)
}
// UsernameByEmail 取得邮箱对应的登录用户名,未找到时原样返回 repository 错误。
func (s *AuthenticationService) UsernameByEmail(ctx context.Context, email string) (string, error) {
if s == nil || s.repository == nil {
return "", errors.New("认证服务未初始化")
}
return s.repository.UsernameByEmail(ctx, email)
}
// Login 校验用户名密码并在成功后创建会话;认证失败返回空会话和 nil 错误以兼容旧 HTTP 行为。
func (s *AuthenticationService) Login(ctx context.Context, username, password string) (string, *AuthUser, error) {
if s == nil || s.repository == nil {
return "", nil, errors.New("认证服务未初始化")
}
// user、matched、verifyErr 保存密码校验得到的身份、匹配结果和基础设施错误。
user, matched, verifyErr := s.repository.VerifyPassword(ctx, username, password)
if verifyErr != nil {
return "", nil, verifyErr
}
if !matched {
return "", nil, nil
}
// sessionID、sessionErr 保存持久化会话的结果,密码不会进入会话端口。
sessionID, sessionErr := s.repository.CreateSession(ctx, user)
if sessionErr != nil {
return "", nil, sessionErr
}
return sessionID, &user, nil
}
// VerifyPassword 校验当前用户密码并返回非敏感身份,供改密和凭据更新复用。
func (s *AuthenticationService) VerifyPassword(ctx context.Context, username, password string) (AuthUser, bool, error) {
if s == nil || s.repository == nil {
return AuthUser{}, false, errors.New("认证服务未初始化")
}
return s.repository.VerifyPassword(ctx, username, password)
}
// UpdatePassword 保存新密码并撤销旧会话,返回值保持数据库层“用户是否存在”的兼容语义。
func (s *AuthenticationService) UpdatePassword(ctx context.Context, username, password string) (bool, error) {
if s == nil || s.repository == nil {
return false, errors.New("认证服务未初始化")
}
return s.repository.UpdatePassword(ctx, username, password)
}
// UpdateCredentials 原子保存用户名及可选密码,并将用户名冲突转换为应用层稳定错误。
func (s *AuthenticationService) UpdateCredentials(ctx context.Context, userID int64, username, password string) error {
if s == nil || s.repository == nil {
return errors.New("认证服务未初始化")
}
return s.repository.UpdateCredentials(ctx, userID, username, password)
}
@@ -0,0 +1,182 @@
package account
import (
"context"
"errors"
"testing"
)
// authenticationRepositoryFake 是认证应用服务测试使用的可控持久化端口替身。
type authenticationRepositoryFake struct {
// initialized、initializedErr 保存系统初始化查询结果及错误。
initialized bool
initializedErr error
// initCreated、initErr 保存管理员初始化结果及错误。
initCreated bool
initErr error
// emailUsername、emailErr 保存邮箱查询结果及错误。
emailUsername string
emailErr error
// verifyUser、verifyMatched、verifyErr 保存密码校验结果及错误。
verifyUser AuthUser
verifyMatched bool
verifyErr error
// sessionID、sessionErr 保存会话创建结果及错误。
sessionID string
sessionErr error
// updatePasswordResult、updatePasswordErr 保存密码更新结果及错误。
updatePasswordResult bool
updatePasswordErr error
// updateCredentialsErr 保存登录凭据更新错误。
updateCredentialsErr error
}
// IsSystemInitialized 返回测试预置的初始化状态。
func (f *authenticationRepositoryFake) IsSystemInitialized(context.Context) (bool, error) {
return f.initialized, f.initializedErr
}
// InitializeAdmin 返回测试预置的管理员初始化结果。
func (f *authenticationRepositoryFake) InitializeAdmin(context.Context, string, string) (bool, error) {
return f.initCreated, f.initErr
}
// UsernameByEmail 返回测试预置的邮箱映射结果。
func (f *authenticationRepositoryFake) UsernameByEmail(context.Context, string) (string, error) {
return f.emailUsername, f.emailErr
}
// VerifyPassword 返回测试预置的密码校验结果。
func (f *authenticationRepositoryFake) VerifyPassword(context.Context, string, string) (AuthUser, bool, error) {
return f.verifyUser, f.verifyMatched, f.verifyErr
}
// UpdatePassword 返回测试预置的密码更新结果。
func (f *authenticationRepositoryFake) UpdatePassword(context.Context, string, string) (bool, error) {
return f.updatePasswordResult, f.updatePasswordErr
}
// UpdateCredentials 返回测试预置的登录凭据更新错误。
func (f *authenticationRepositoryFake) UpdateCredentials(context.Context, int64, string, string) error {
return f.updateCredentialsErr
}
// CreateSession 返回测试预置的会话创建结果。
func (f *authenticationRepositoryFake) CreateSession(context.Context, AuthUser) (string, error) {
return f.sessionID, f.sessionErr
}
// TestNewAuthenticationServiceRequiresRepository 验证认证服务拒绝缺少持久化端口。
func TestNewAuthenticationServiceRequiresRepository(t *testing.T) {
// service、serviceErr 保存缺少 repository 时的构造结果。
service, serviceErr := NewAuthenticationService(nil)
if service != nil || serviceErr == nil {
t.Fatalf("缺少 repository 应构造失败 service=%v err=%v", service, serviceErr)
}
}
// TestAuthenticationServiceLoginBranches 覆盖登录成功、认证失败、校验错误和会话写入错误。
func TestAuthenticationServiceLoginBranches(t *testing.T) {
// sessionErr 是模拟会话写入失败的固定错误。
sessionErr := errors.New("session unavailable")
// verifyErr 是模拟密码校验基础设施失败的固定错误。
verifyErr := errors.New("verify unavailable")
// testCases 保存登录分支及其预期结果。
testCases := []struct {
// name 是当前分支的可读名称。
name string
// repository 是当前分支使用的认证端口替身。
repository *authenticationRepositoryFake
// wantSession 表示预期返回的会话 ID。
wantSession string
// wantUser 表示预期返回的非敏感用户身份是否存在。
wantUser bool
// wantErr 表示预期返回的错误。
wantErr error
}{
{name: "success", repository: &authenticationRepositoryFake{
verifyUser: AuthUser{ID: 7, Username: "admin", IsAdmin: true}, verifyMatched: true, sessionID: "sid-1",
}, wantSession: "sid-1", wantUser: true},
{name: "mismatch", repository: &authenticationRepositoryFake{}, wantErr: nil},
{name: "verify error", repository: &authenticationRepositoryFake{verifyErr: verifyErr}, wantErr: verifyErr},
{name: "session error", repository: &authenticationRepositoryFake{
verifyUser: AuthUser{ID: 7, Username: "admin"}, verifyMatched: true, sessionErr: sessionErr,
}, wantErr: sessionErr},
}
// testCase 表示当前遍历到的登录分支测试参数。
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
// service、serviceErr 保存当前分支的认证服务构造结果。
service, serviceErr := NewAuthenticationService(testCase.repository)
if serviceErr != nil {
t.Fatalf("构造认证服务失败: %v", serviceErr)
}
// sessionID、user、loginErr 保存当前分支的登录结果。
sessionID, user, loginErr := service.Login(context.Background(), "admin", "password")
if !errors.Is(loginErr, testCase.wantErr) || sessionID != testCase.wantSession || (user != nil) != testCase.wantUser {
t.Fatalf("登录结果 session=%q user=%+v err=%v", sessionID, user, loginErr)
}
})
}
}
// TestAuthenticationServiceDelegatesAccountOperations 验证初始化、邮箱查询和改密操作保持端口结果。
func TestAuthenticationServiceDelegatesAccountOperations(t *testing.T) {
// repository 是预置全部成功结果的认证端口替身。
repository := &authenticationRepositoryFake{
initialized: true, initCreated: true, emailUsername: "admin", verifyUser: AuthUser{ID: 7}, verifyMatched: true,
updatePasswordResult: true,
}
// service、serviceErr 保存认证应用服务构造结果。
service, serviceErr := NewAuthenticationService(repository)
if serviceErr != nil {
t.Fatalf("构造认证服务失败: %v", serviceErr)
}
// initialized、initializedErr 保存初始化状态查询结果。
initialized, initializedErr := service.IsSystemInitialized(context.Background())
if initializedErr != nil || !initialized {
t.Fatalf("初始化状态异常 initialized=%v err=%v", initialized, initializedErr)
}
// created、createErr 保存管理员初始化结果。
created, createErr := service.InitializeAdmin(context.Background(), "admin@example.com", "password")
if createErr != nil || !created {
t.Fatalf("管理员初始化异常 created=%v err=%v", created, createErr)
}
// username、usernameErr 保存邮箱映射结果。
username, usernameErr := service.UsernameByEmail(context.Background(), "admin@example.com")
if usernameErr != nil || username != "admin" {
t.Fatalf("邮箱登录名异常 username=%q err=%v", username, usernameErr)
}
// user、matched、verifyErr 保存当前密码校验结果。
user, matched, verifyErr := service.VerifyPassword(context.Background(), "admin", "password")
if verifyErr != nil || !matched || user.ID != 7 {
t.Fatalf("密码校验异常 user=%+v matched=%v err=%v", user, matched, verifyErr)
}
// updated、updateErr 保存密码更新结果。
updated, updateErr := service.UpdatePassword(context.Background(), "admin", "new-password")
if updateErr != nil || !updated {
t.Fatalf("密码更新异常 updated=%v err=%v", updated, updateErr)
}
// credentialsErr 保存登录凭据更新结果。
if credentialsErr := service.UpdateCredentials(context.Background(), 7, "operator", "new-password"); credentialsErr != nil {
t.Fatalf("登录凭据更新异常: %v", credentialsErr)
}
}
// TestAuthenticationServicePreservesCredentialErrors 验证认证服务不吞掉底层更新错误。
func TestAuthenticationServicePreservesCredentialErrors(t *testing.T) {
// updateErr 是模拟凭据更新失败的固定错误。
updateErr := errors.New("credential update unavailable")
// repository 是返回凭据更新错误的认证端口替身。
repository := &authenticationRepositoryFake{updateCredentialsErr: updateErr}
// service、serviceErr 保存认证应用服务构造结果。
service, serviceErr := NewAuthenticationService(repository)
if serviceErr != nil {
t.Fatalf("构造认证服务失败: %v", serviceErr)
}
// credentialsErr 保存应用服务透传的凭据更新错误。
credentialsErr := service.UpdateCredentials(context.Background(), 7, "operator", "password")
if !errors.Is(credentialsErr, updateErr) {
t.Fatalf("凭据更新错误未透传 got=%v want=%v", credentialsErr, updateErr)
}
}
@@ -0,0 +1,45 @@
package account
import (
"context"
"errors"
)
// ErrCredentialNotFound 表示平台凭证查询目标账号不存在;调用方无需依赖数据库错误类型。
var ErrCredentialNotFound = errors.New("平台凭证账号不存在")
// CredentialDetail 是账号凭证流程需要的最小平台视图;不包含登录用户名、密码或其他秘密。
type CredentialDetail struct {
// ID 是账号稳定标识,用于凭证更新和运行时关联。
ID string
// UserID 是账号所属本地用户标识,用于所有权复核。
UserID int64
// Value 是仅在平台调用边界短暂存在的 Cookie 明文,禁止进入日志、HTTP DTO 或长期应用状态。
Value string
// MetadataJSON 是由数据库适配器管理的加密 Cookie 元数据,不应由 Server 解析或序列化。
MetadataJSON string
// ShowBrowser 表示平台登录流程是否允许显示浏览器。
ShowBrowser bool
// LastRefreshAt 是客户端乐观冲突检查使用的最近刷新时间,单位为 Unix 秒。
LastRefreshAt int64
}
// CredentialRepository 定义账号 Cookie 登录与平台运行态更新所需的最小持久化端口。
type CredentialRepository interface {
// LockCredentials 串行化同一账号的凭证写入和平台资料会话。
LockCredentials(string) func()
// CreateCookieOwned 原子校验账号归属并创建 Cookie;明文只在适配器内部进入加密存储。
CreateCookieOwned(context.Context, string, string, int64) error
// LoadPlatformDetail 读取平台调用所需的窄视图,不读取登录密码。
LoadPlatformDetail(context.Context, string) (*CredentialDetail, error)
// UpdateFlatCookieOwned 更新扁平 Cookie 并清除旧的完整快照。
UpdateFlatCookieOwned(context.Context, *CredentialDetail, string) error
// UpdateRenewalCookie 保存平台返回的 Cookie 与 metadata;明文只在凭证适配器内短暂存在。
UpdateRenewalCookie(context.Context, string, string, string, int64) error
// ClearTokens 清理凭证变化后失效的旧连接 Token。
ClearTokens(context.Context, string) error
// GetStatus 查询账号是否启用;数据库故障按停用处理。
GetStatus(context.Context, string) bool
// UpdateProfile 保存不含凭证的账号展示资料。
UpdateProfile(context.Context, string, string, string) error
}
@@ -9,8 +9,8 @@ import (
// ErrDeleteConflict 表示账号运行时尚未收束,删除操作不会覆盖仍存活的实例。
var ErrDeleteConflict = errors.New("账号正在停止,请稍后重试")
// DeleteRepository 定义账号删除用例所需的最小非敏感持久化端口。
type DeleteRepository interface {
// DeleteSummaryRepository 定义账号删除用例所需的最小非敏感持久化端口。
type DeleteSummaryRepository interface {
// GetOwnedSummary 按用户和账号联合查询非敏感摘要,用于删除前归属确认。
GetOwnedSummary(context.Context, int64, string) (Summary, error)
// DeleteOwned 在基础设施边界再次确认归属后删除账号及其关联数据。
@@ -30,13 +30,13 @@ type DeleteRuntime interface {
// DeleteService 编排账号归属校验、运行时 fencing 和关联数据删除。
type DeleteService struct {
// repository 提供非敏感账号查询和按归属删除能力。
repository DeleteRepository
repository DeleteSummaryRepository
// runtime 提供可选的账号运行时停止能力;为空时仅执行持久化删除。
runtime DeleteRuntime
}
// NewDeleteService 构造账号删除应用服务并校验必需的持久化端口。
func NewDeleteService(repository DeleteRepository, runtime DeleteRuntime) (*DeleteService, error) {
func NewDeleteService(repository DeleteSummaryRepository, runtime DeleteRuntime) (*DeleteService, error) {
if repository == nil {
return nil, errors.New("账号删除 repository 未初始化")
}
+162
View File
@@ -0,0 +1,162 @@
package account
import (
"context"
"errors"
"strings"
"time"
)
const (
// LoginMethodManual 表示用户直接录入或更新 Cookie 的登录方式。
LoginMethodManual = "manual"
// LoginMethodPassword 表示账号密码登录方式。
LoginMethodPassword = "password"
// LoginMethodQRScan 表示扫码登录方式。
LoginMethodQRScan = "qr_scan"
// LoginStatusSuccess 表示登录审计成功状态。
LoginStatusSuccess = "success"
)
var (
// ErrLoginAuditUnavailable 表示登录审计服务缺少必需的持久化端口。
ErrLoginAuditUnavailable = errors.New("账号登录审计服务未初始化")
)
// LoginAuditLog 是登录审计写入模型,不携带 Cookie、Token 或登录密码。
type LoginAuditLog struct {
// AccountID 是产生登录事件的账号稳定标识。
AccountID string
// UserID 是触发登录操作的本地用户标识。
UserID int64
// Method 是归一化后的登录方式。
Method string
// Status 是登录尝试的结果状态。
Status string
// Message 是面向运维审计的非敏感结果摘要。
Message string
// TriggerReason 是由登录方式推导出的触发原因。
TriggerReason string
// FailureReason 是可选的稳定失败分类。
FailureReason string
// OccurredAt 是 Unix 秒时间戳,用于保持数据库审计记录的时间顺序。
OccurredAt int64
}
// SuccessfulLoginInput 是登录凭证写入成功后的审计输入,不包含任何凭证内容。
type SuccessfulLoginInput struct {
// AccountID 是刚完成登录的账号稳定标识。
AccountID string
// UserID 是当前登录操作所属的本地用户标识。
UserID int64
// Method 是调用方提供的登录方式或兼容别名。
Method string
// Message 是写入审计日志的非敏感成功摘要。
Message string
// OccurredAt 是可选的 Unix 秒时间戳;零值由服务使用当前时间填充。
OccurredAt int64
}
// LoginAuditRepository 定义登录成功审计所需的最小持久化端口。
type LoginAuditRepository interface {
// MarkLogin 保存账号最近一次成功登录方式和时间。
MarkLogin(context.Context, string, string, int64) error
// SetStatusWithReason 在登录成功后启用账号并保存状态原因。
SetStatusWithReason(context.Context, string, bool, string) error
// AddLoginLog 写入不含敏感凭证的登录审计记录。
AddLoginLog(context.Context, LoginAuditLog) error
}
// LoginAuditService 编排登录成功后的方式记录、账号启用和审计日志写入。
type LoginAuditService struct {
// repository 提供登录审计所需的三项窄持久化能力。
repository LoginAuditRepository
}
// NewLoginAuditService 构造登录审计应用服务。
func NewLoginAuditService(repository LoginAuditRepository) *LoginAuditService {
return &LoginAuditService{repository: repository}
}
// RecordSuccessfulLogin 记录成功登录并按登录方式启用账号;后续写入失败不会泄露凭证。
func (s *LoginAuditService) RecordSuccessfulLogin(ctx context.Context, input SuccessfulLoginInput) error {
if s == nil || s.repository == nil {
return ErrLoginAuditUnavailable
}
if strings.TrimSpace(input.AccountID) == "" || strings.TrimSpace(input.Method) == "" {
return nil
}
// method 是审计和账号状态更新共用的稳定登录方式。
method := NormalizeLoginMethod(input.Method)
// occurredAt 是本次成功登录的审计时间;调用方可注入固定时间以保证重放一致。
occurredAt := input.OccurredAt
if occurredAt == 0 {
occurredAt = time.Now().Unix()
}
// markErr 表示最近登录方式持久化失败;失败时不应继续伪造成功状态或日志。
if markErr := s.repository.MarkLogin(ctx, input.AccountID, method, occurredAt); markErr != nil {
return markErr
}
// writeErrors 收集独立写入阶段的错误,同时保证状态写入失败时仍尝试保存审计日志。
var writeErrors []error
if method == LoginMethodPassword || method == LoginMethodQRScan {
// statusErr 表示登录成功后启用账号失败,但不阻止继续留下审计日志。
if statusErr := s.repository.SetStatusWithReason(ctx, input.AccountID, true, ""); statusErr != nil {
writeErrors = append(writeErrors, statusErr)
}
}
// log 是由应用层字段组成的审计记录,数据库模型转换留在适配器内。
log := LoginAuditLog{
AccountID: input.AccountID,
UserID: input.UserID,
Method: method,
Status: LoginStatusSuccess,
Message: truncateLoginMessage(input.Message, 500),
TriggerReason: loginTriggerReason(method),
OccurredAt: occurredAt,
}
// logErr 表示成功登录审计日志写入失败,需要与账号状态错误一起返回。
if logErr := s.repository.AddLoginLog(ctx, log); logErr != nil {
writeErrors = append(writeErrors, logErr)
}
return errors.Join(writeErrors...)
}
// NormalizeLoginMethod 将兼容的登录方式别名归一化为稳定审计值。
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))
}
}
// loginTriggerReason 将稳定登录方式转换为审计展示原因。
func loginTriggerReason(method string) string {
switch NormalizeLoginMethod(method) {
case LoginMethodManual:
return "手动Cookie录入"
case LoginMethodPassword:
return "账号密码登录"
case LoginMethodQRScan:
return "扫码登录"
default:
return ""
}
}
// truncateLoginMessage 限制审计摘要长度,避免外部错误文本膨胀持久化记录。
func truncateLoginMessage(message string, limit int) string {
if limit <= 0 {
return ""
}
if len(message) <= limit {
return message
}
return message[:limit]
}
@@ -0,0 +1,121 @@
package account
import (
"context"
"errors"
"testing"
)
// fakeLoginAuditRepository 记录登录审计应用服务调用并注入各阶段错误。
type fakeLoginAuditRepository struct {
// markErr、statusErr、logErr 分别模拟登录方式、账号状态和审计日志写入失败。
markErr error
statusErr error
logErr error
// markCalls、statusCalls、logs 保存各持久化阶段的调用结果。
markCalls int
statusCalls int
logs []LoginAuditLog
}
// MarkLogin 记录最近一次成功登录方式写入请求。
func (r *fakeLoginAuditRepository) MarkLogin(_ context.Context, _ string, _ string, _ int64) error {
r.markCalls++
return r.markErr
}
// SetStatusWithReason 记录登录成功后的账号启用请求。
func (r *fakeLoginAuditRepository) SetStatusWithReason(_ context.Context, _ string, _ bool, _ string) error {
r.statusCalls++
return r.statusErr
}
// AddLoginLog 保存应用层登录审计模型,供测试核对敏感字段未被引入。
func (r *fakeLoginAuditRepository) AddLoginLog(_ context.Context, log LoginAuditLog) error {
r.logs = append(r.logs, log)
return r.logErr
}
// TestLoginAuditServiceRequiresRepository 验证缺少持久化端口时服务返回明确错误。
func TestLoginAuditServiceRequiresRepository(t *testing.T) {
// service 是没有仓储端口的零值审计服务。
service := NewLoginAuditService(nil)
// recordErr 保存缺少依赖时的执行错误。
recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodManual})
if !errors.Is(recordErr, ErrLoginAuditUnavailable) {
t.Fatalf("缺少审计仓储时错误=%v", recordErr)
}
}
// TestLoginAuditServiceManualSuccessWritesLog 验证手动登录只记录方式和审计日志,不重复启用账号。
func TestLoginAuditServiceManualSuccessWritesLog(t *testing.T) {
// repository 是记录持久化调用的审计仓储替身。
repository := &fakeLoginAuditRepository{}
// service 是使用测试仓储构造的应用服务。
service := NewLoginAuditService(repository)
// recordErr 保存固定时间的手动登录审计结果。
recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", UserID: 7, Method: "cookie", Message: "登录成功", OccurredAt: 42})
if recordErr != nil {
t.Fatalf("记录手动登录失败: %v", recordErr)
}
if repository.markCalls != 1 || repository.statusCalls != 0 || len(repository.logs) != 1 {
t.Fatalf("持久化阶段调用异常: %+v", repository)
}
if repository.logs[0].Method != LoginMethodManual || repository.logs[0].TriggerReason != "手动Cookie录入" || repository.logs[0].OccurredAt != 42 {
t.Fatalf("登录审计模型异常: %+v", repository.logs[0])
}
}
// TestLoginAuditServicePasswordEnablesAccount 验证密码和扫码登录成功后会启用账号并记录日志。
func TestLoginAuditServicePasswordEnablesAccount(t *testing.T) {
// repository 是记录账号状态与日志写入的审计仓储替身。
repository := &fakeLoginAuditRepository{}
// service 是使用测试仓储构造的应用服务。
service := NewLoginAuditService(repository)
// recordErr 保存密码登录成功的审计结果。
recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", UserID: 7, Method: "password_login"})
if recordErr != nil {
t.Fatalf("记录密码登录失败: %v", recordErr)
}
if repository.statusCalls != 1 || len(repository.logs) != 1 || repository.logs[0].Method != LoginMethodPassword {
t.Fatalf("密码登录启用与日志调用异常: %+v", repository)
}
}
// TestLoginAuditServiceJoinsIndependentWriteFailures 验证状态与日志独立失败时保留两类错误。
func TestLoginAuditServiceJoinsIndependentWriteFailures(t *testing.T) {
// statusErr、logErr 是两个相互独立的持久化故障。
statusErr := errors.New("启用账号失败")
// logErr 表示登录审计日志独立写入失败。
logErr := errors.New("写入审计失败")
// repository 注入两个独立故障,确认服务仍尝试写日志。
repository := &fakeLoginAuditRepository{statusErr: statusErr, logErr: logErr}
// service 是使用故障仓储构造的应用服务。
service := NewLoginAuditService(repository)
// recordErr 保存合并后的审计错误。
recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodQRScan})
if !errors.Is(recordErr, statusErr) || !errors.Is(recordErr, logErr) {
t.Fatalf("应保留状态和日志双重错误: %v", recordErr)
}
if len(repository.logs) != 1 {
t.Fatal("状态写入失败后仍应尝试记录审计日志")
}
}
// TestLoginAuditServiceStopsAfterMarkFailure 验证最近登录方式写入失败时不会伪造后续成功记录。
func TestLoginAuditServiceStopsAfterMarkFailure(t *testing.T) {
// markErr 是最近登录方式写入失败。
markErr := errors.New("记录登录方式失败")
// repository 注入方式写入故障。
repository := &fakeLoginAuditRepository{markErr: markErr}
// service 是使用故障仓储构造的应用服务。
service := NewLoginAuditService(repository)
// recordErr 保存方式写入失败结果。
recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodManual})
if !errors.Is(recordErr, markErr) {
t.Fatalf("应返回方式写入错误: %v", recordErr)
}
if repository.statusCalls != 0 || len(repository.logs) != 0 {
t.Fatal("方式写入失败时不应继续伪造成功状态或日志")
}
}
+2 -16
View File
@@ -80,7 +80,7 @@ func (s *LoginService) CreateCookie(ctx context.Context, input CreateCookieInput
return writeErr
}
// method 是归一化后的登录方式,供审计和运行时适配器保持统一语义。
method := normalizeLoginMethod(input.LoginMethod)
method := NormalizeLoginMethod(input.LoginMethod)
s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method)
return nil
}
@@ -104,22 +104,8 @@ func (s *LoginService) UpdateCookie(ctx context.Context, input UpdateCookieInput
// method 是归一化后的登录方式;更新凭证未声明登录方式时必须保持普通替换,不写入登录审计。
method := ""
if strings.TrimSpace(input.LoginMethod) != "" {
method = normalizeLoginMethod(input.LoginMethod)
method = NormalizeLoginMethod(input.LoginMethod)
}
s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method)
return nil
}
// normalizeLoginMethod 将兼容的登录方式别名归一化为审计使用的稳定值。
func normalizeLoginMethod(method string) string {
switch strings.ToLower(strings.TrimSpace(method)) {
case "", "manual", "cookie", "manual_cookie":
return "manual"
case "password", "password_login":
return "password"
case "qr", "qr_login", "qr_scan":
return "qr_scan"
default:
return strings.ToLower(strings.TrimSpace(method))
}
}
@@ -0,0 +1,68 @@
package account
import (
"context"
"errors"
)
// ErrLongLoginPlatform 表示长登录平台请求失败;响应 Cookie 仍可能已经被适配器持久化。
var ErrLongLoginPlatform = errors.New("长登录平台请求失败")
// LongLoginResult 是长登录设置接口的非敏感结果,不携带平台 Cookie 或响应头。
type LongLoginResult struct {
// CanOpenLongLogin 表示平台是否允许当前账号使用长登录。
CanOpenLongLogin bool
// Enabled 表示平台当前是否已开启长登录。
Enabled bool
}
// LongLoginPort 定义长登录平台请求及凭证持久化所需的最小端口。
type LongLoginPort interface {
// QueryLongLogin 查询指定账号的长登录状态,并在适配器内处理响应 Cookie。
QueryLongLogin(context.Context, string) (LongLoginResult, error)
// SetLongLogin 更新指定账号的长登录开关,并在适配器内处理响应 Cookie。
SetLongLogin(context.Context, string, bool) (LongLoginResult, error)
}
// LongLoginService 编排长登录设置的账号归属校验和平台操作。
type LongLoginService struct {
// repository 提供不解密凭证的账号归属查询能力。
repository ProfileSummaryRepository
// port 承担平台请求、Cookie 快照合并和凭证持久化。
port LongLoginPort
}
// NewLongLoginService 构造长登录应用服务并校验必需端口。
func NewLongLoginService(repository ProfileSummaryRepository, port LongLoginPort) (*LongLoginService, error) {
if repository == nil {
return nil, errors.New("长登录账号摘要 repository 未初始化")
}
if port == nil {
return nil, errors.New("长登录平台端口未初始化")
}
return &LongLoginService{repository: repository, port: port}, nil
}
// Query 查询当前用户拥有账号的长登录状态。
func (s *LongLoginService) Query(ctx context.Context, userID int64, accountID string) (LongLoginResult, error) {
if s == nil || s.repository == nil || s.port == nil {
return LongLoginResult{}, errors.New("长登录服务未初始化")
}
// summary 保存归属校验使用的非敏感账号摘要。
if _, err := s.repository.GetOwnedSummary(ctx, userID, accountID); err != nil {
return LongLoginResult{}, err
}
return s.port.QueryLongLogin(ctx, accountID)
}
// Set 更新当前用户拥有账号的长登录开关。
func (s *LongLoginService) Set(ctx context.Context, userID int64, accountID string, enabled bool) (LongLoginResult, error) {
if s == nil || s.repository == nil || s.port == nil {
return LongLoginResult{}, errors.New("长登录服务未初始化")
}
// summary 保存归属校验使用的非敏感账号摘要。
if _, err := s.repository.GetOwnedSummary(ctx, userID, accountID); err != nil {
return LongLoginResult{}, err
}
return s.port.SetLongLogin(ctx, accountID, enabled)
}
@@ -0,0 +1,72 @@
package account
import (
"context"
"errors"
"testing"
)
// longLoginSummaryRepositoryFake 是长登录用例测试使用的非敏感摘要仓储替身。
type longLoginSummaryRepositoryFake struct {
// summary 保存归属校验成功时返回的账号摘要。
summary Summary
// err 保存摘要查询失败时返回的错误。
err error
}
// GetOwnedSummary 返回预设的账号摘要或归属错误。
func (f longLoginSummaryRepositoryFake) GetOwnedSummary(context.Context, int64, string) (Summary, error) {
return f.summary, f.err
}
// longLoginPortFake 是长登录用例测试使用的平台端口替身。
type longLoginPortFake struct {
// result 保存平台请求成功时返回的非敏感状态。
result LongLoginResult
// calls 记录平台调用次数,用于确认归属失败不会访问平台。
calls int
}
// QueryLongLogin 返回预设的长登录查询结果。
func (f *longLoginPortFake) QueryLongLogin(context.Context, string) (LongLoginResult, error) {
f.calls++
return f.result, nil
}
// SetLongLogin 返回预设的长登录设置结果。
func (f *longLoginPortFake) SetLongLogin(context.Context, string, bool) (LongLoginResult, error) {
f.calls++
return f.result, nil
}
// TestLongLoginServiceChecksOwnershipAndMapsResult 验证长登录用例先校验归属,再返回脱敏状态。
func TestLongLoginServiceChecksOwnershipAndMapsResult(t *testing.T) {
// port 保存平台端口替身及调用计数。
port := &longLoginPortFake{result: LongLoginResult{CanOpenLongLogin: true, Enabled: true}}
// service、serviceErr 保存长登录应用服务及其装配错误。
service, serviceErr := NewLongLoginService(longLoginSummaryRepositoryFake{summary: Summary{ID: "account-1"}}, port)
if serviceErr != nil {
t.Fatal(serviceErr)
}
// result、callErr 保存长登录查询结果和平台调用错误。
result, callErr := service.Query(context.Background(), 1, "account-1")
if callErr != nil || result != (LongLoginResult{CanOpenLongLogin: true, Enabled: true}) || port.calls != 1 {
t.Fatalf("result=%+v err=%v calls=%d", result, callErr, port.calls)
}
}
// TestLongLoginServiceStopsOnOwnershipError 验证账号归属失败时不会调用平台端口。
func TestLongLoginServiceStopsOnOwnershipError(t *testing.T) {
// port 保存平台端口替身及调用计数。
port := &longLoginPortFake{}
// service、serviceErr 保存长登录应用服务及其装配错误。
service, serviceErr := NewLongLoginService(longLoginSummaryRepositoryFake{err: ErrForbidden}, port)
if serviceErr != nil {
t.Fatal(serviceErr)
}
// callErr 保存归属校验返回的应用错误。
_, callErr := service.Set(context.Background(), 1, "account-1", true)
if !errors.Is(callErr, ErrForbidden) || port.calls != 0 {
t.Fatalf("err=%v calls=%d", callErr, port.calls)
}
}
@@ -24,6 +24,24 @@ type Summary struct {
Nickname string
// AvatarURL 是本地缓存的平台头像地址,用于资料刷新失败时的展示兜底。
AvatarURL string
// AutoConfirm 表示账号是否启用自动确认收货。
AutoConfirm bool
// PauseDuration 是账号暂停时长,单位为分钟。
PauseDuration int
// PausedUntil 是暂停结束时间的 Unix 秒;零值表示当前未暂停。
PausedUntil int64
// Username 是账号关联的登录用户名,不包含登录密码。
Username string
// ShowBrowser 表示密码登录流程是否允许显示浏览器。
ShowBrowser bool
// LastRefreshAt 是最近一次资料刷新时间,单位为 Unix 秒。
LastRefreshAt int64
// LoginMethod 是最近一次成功登录方式,不包含凭证内容。
LoginMethod string
// LastLoginAt 是最近一次成功登录时间,单位为 Unix 秒。
LastLoginAt int64
// CreatedAt 是账号记录创建时间的数据库字符串。
CreatedAt string
}
// ProfileInput 是平台资料刷新端口的输入,携带已通过归属校验的账号摘要。
@@ -48,8 +66,8 @@ type ProfileResult struct {
ErrorMessage string
}
// SummaryRepository 定义资料刷新用例读取账号归属和摘要所需的最小端口。
type SummaryRepository interface {
// ProfileSummaryRepository 定义资料刷新用例读取账号归属和摘要所需的最小端口。
type ProfileSummaryRepository interface {
// GetOwnedSummary 按用户和账号联合查询非敏感摘要;不存在或越权时返回错误。
GetOwnedSummary(context.Context, int64, string) (Summary, error)
}
@@ -63,13 +81,13 @@ type ProfilePort interface {
// ProfileService 编排账号归属校验、平台资料刷新和可展示结果转换。
type ProfileService struct {
// repository 提供不解密凭证的账号摘要查询能力。
repository SummaryRepository
repository ProfileSummaryRepository
// profilePort 承担平台调用、凭证会话更新和资料持久化适配。
profilePort ProfilePort
}
// NewProfileService 构造资料刷新应用服务并校验必需端口。
func NewProfileService(repository SummaryRepository, profilePort ProfilePort) (*ProfileService, error) {
func NewProfileService(repository ProfileSummaryRepository, profilePort ProfilePort) (*ProfileService, error) {
if repository == nil {
return nil, errors.New("账号资料摘要 repository 未初始化")
}
@@ -46,7 +46,7 @@ func TestNewProfileServiceRequiresPorts(t *testing.T) {
// name 是当前构造失败场景名称。
name string
// repository 是当前场景使用的摘要端口。
repository SummaryRepository
repository ProfileSummaryRepository
// profilePort 是当前场景使用的平台端口。
profilePort ProfilePort
}{
@@ -12,6 +12,9 @@ var ErrQRLoginIncomplete = errors.New("扫码结果缺少账号标识或 cookies
// ErrQRLoginAccountMismatch 表示扫码得到的平台账号与待重新授权账号不一致。
var ErrQRLoginAccountMismatch = errors.New("扫码账号与待重新授权账号不一致")
// ErrAlreadyExists 表示扫码创建账号时目标标识已被并发请求占用。
var ErrAlreadyExists = errors.New("账号已存在")
// CookieSnapshot 是浏览器返回的单个 Cookie 快照;明文值只在当前凭证适配端口调用期间存在。
type CookieSnapshot struct {
// Name 是浏览器 Cookie 名称。
@@ -0,0 +1,228 @@
package account
import (
"context"
"errors"
)
// SettingsUpdateInput 是账号编辑用例的输入;Password 为 nil 时保留数据库中的既有密码。
type SettingsUpdateInput struct {
// UserID 是当前认证用户的本地身份标识,用于数据库边界的归属复核。
UserID int64
// AccountID 是待更新的闲鱼账号稳定标识。
AccountID string
// Cookie 是可选的新 Cookie 明文,只在数据库适配器调用期间短暂存在。
Cookie *string
// Remark 是可选的账号备注更新值。
Remark *string
// AutoConfirm 是可选的自动确认发货开关。
AutoConfirm *bool
// PauseDuration 是可选的暂停时长,单位为分钟;零表示立即恢复。
PauseDuration *int
// Username 是可选的密码登录用户名更新值。
Username *string
// Password 是可选的密码登录秘密;空字符串用于明确清除密码。
Password *string
// ShowBrowser 是可选的密码登录浏览器显示开关。
ShowBrowser *bool
// ChannelIDs 是可选的通知渠道绑定集合;空切片表示解绑全部渠道。
ChannelIDs *[]int64
}
// LoginInfoUpdateInput 是账号登录信息用例的输入,不暴露既有密码读取能力。
type LoginInfoUpdateInput struct {
// UserID 是当前认证用户的本地身份标识。
UserID int64
// AccountID 是待更新账号的稳定标识。
AccountID string
// Username 是登录用户名;该接口保持旧 HTTP API 的空字符串覆盖语义。
Username string
// Password 是可选的新密码;nil 表示保留既有密码,空字符串表示清除密码。
Password *string
// ShowBrowser 表示登录时是否允许显示浏览器。
ShowBrowser bool
}
// PauseState 是账号暂停查询的非敏感结果。
type PauseState struct {
// Duration 是账号配置的暂停时长,单位为分钟。
Duration int
// PausedUntil 是暂停截止时间的 Unix 秒;零表示当前没有截止时间。
PausedUntil int64
// Paused 表示当前时间是否仍处于暂停窗口内。
Paused bool
}
// SettingsResult 是账号设置写入后的业务结果。
type SettingsResult struct {
// PausedUntil 是写入后暂停截止时间的 Unix 秒。
PausedUntil int64
// RuntimeError 是持久化成功后运行时重启失败的诊断信息;不会回滚数据库写入。
RuntimeError error
// TokenCleanupError 是 Cookie 写入成功后清理旧连接凭证的错误;不会回滚账号设置。
TokenCleanupError error
}
// StatusResult 是账号启停写入后的业务结果。
type StatusResult struct {
// RuntimeError 是状态写入成功后运行时启停失败的诊断信息。
RuntimeError error
}
// SettingsRepository 定义账号设置用例需要的最小持久化端口。
type SettingsRepository interface {
// LockCredentials 串行化同一账号的敏感设置写入;调用方必须及时释放返回的函数。
LockCredentials(string) func()
// UpdateSettings 原子更新账号设置并按 UserID 复核账号归属。
UpdateSettings(context.Context, SettingsUpdateInput) (int64, error)
// UpdateLoginInfo 原子更新用户名、密码和浏览器显示设置并按 UserID 复核归属。
UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error
// SetStatusOwned 更新账号启用状态并按 UserID 复核归属。
SetStatusOwned(context.Context, int64, string, bool, string) error
// StatusOwned 查询指定用户账号的启用状态,不读取凭证明文。
StatusOwned(context.Context, int64, string) (bool, error)
// SetPauseOwned 更新账号暂停时长并按 UserID 复核归属。
SetPauseOwned(context.Context, int64, string, int) (int64, error)
// GetPauseOwned 查询指定用户账号的暂停状态,不读取凭证明文。
GetPauseOwned(context.Context, int64, string) (PauseState, error)
// ClearTokens 清理 Cookie 变更后失效的旧连接凭证。
ClearTokens(context.Context, string) error
}
// SettingsRuntime 定义账号设置变更后运行实例的最小控制端口。
type SettingsRuntime interface {
// Restart 在账号启用且 Cookie 变化后重新加载运行实例。
Restart(context.Context, string) error
// Stop 在账号停用后停止运行实例。
Stop(string)
}
// SettingsService 编排账号设置、登录信息、状态和暂停用例,不依赖 HTTP 或数据库模型。
type SettingsService struct {
// repository 提供账号设置的窄持久化能力。
repository SettingsRepository
// runtime 提供可选的账号运行实例控制能力。
runtime SettingsRuntime
}
// NewSettingsService 构造账号设置应用服务并校验必需的持久化端口。
func NewSettingsService(repository SettingsRepository, runtime SettingsRuntime) (*SettingsService, error) {
if repository == nil {
return nil, errors.New("账号设置 repository 未初始化")
}
return &SettingsService{repository: repository, runtime: runtime}, nil
}
// UpdateSettings 原子保存账号设置;Cookie 变化后的运行时重启在释放凭证锁后执行。
func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpdateInput) (SettingsResult, error) {
if s == nil || s.repository == nil {
return SettingsResult{}, errors.New("账号设置服务未初始化")
}
if input.AccountID == "" {
return SettingsResult{}, errors.New("缺少账号 ID")
}
// unlock 负责释放本次账号设置写入的凭证锁。
unlock := s.repository.LockCredentials(input.AccountID)
// pausedUntil、updateErr 保存设置事务返回的暂停截止时间和错误。
pausedUntil, updateErr := s.repository.UpdateSettings(ctx, input)
unlock()
if updateErr != nil {
return SettingsResult{}, updateErr
}
// result 保存设置写入及后续运行时处理结果。
result := SettingsResult{PausedUntil: pausedUntil}
if input.Cookie != nil {
// tokenErr 记录 Cookie 替换后清理旧连接凭证的错误;主设置写入已成功,不能回滚。
tokenErr := s.repository.ClearTokens(ctx, input.AccountID)
result.TokenCleanupError = tokenErr
}
if input.Cookie != nil && s.runtime != nil {
// enabled 表示写入成功后账号的最新启用状态;状态读取失败不覆盖已成功的设置写入。
enabled, statusErr := s.repository.StatusOwned(ctx, input.UserID, input.AccountID)
if statusErr == nil && enabled {
result.RuntimeError = s.runtime.Restart(ctx, input.AccountID)
}
}
return result, nil
}
// UpdateLoginInfo 保存账号用户名、密码和浏览器显示设置;既有密码不会被应用层读取。
func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUpdateInput) error {
if s == nil || s.repository == nil {
return errors.New("账号设置服务未初始化")
}
if input.AccountID == "" {
return errors.New("缺少账号 ID")
}
// unlock 负责释放登录信息写入期间持有的凭证锁。
unlock := s.repository.LockCredentials(input.AccountID)
defer unlock()
return s.repository.UpdateLoginInfo(ctx, input)
}
// SetStatus 更新账号启用状态并在持久化成功后控制运行实例。
func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID string, enabled bool) (StatusResult, error) {
if s == nil || s.repository == nil {
return StatusResult{}, errors.New("账号设置服务未初始化")
}
if accountID == "" {
return StatusResult{}, errors.New("缺少账号 ID")
}
// reason 由应用层统一产生,避免 HTTP 层决定持久化状态原因。
reason := ""
if !enabled {
reason = "manual"
}
// unlock 负责释放账号状态写入期间持有的凭证锁。
unlock := s.repository.LockCredentials(accountID)
// statusErr 保存账号状态持久化错误。
statusErr := s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason)
unlock()
if statusErr != nil {
return StatusResult{}, statusErr
}
// result 保存状态写入后运行时启停的结果。
result := StatusResult{}
if s.runtime != nil {
if enabled {
result.RuntimeError = s.runtime.Restart(ctx, accountID)
} else {
s.runtime.Stop(accountID)
}
}
return result, nil
}
// SetAutoConfirm 更新账号自动确认发货开关。
func (s *SettingsService) SetAutoConfirm(ctx context.Context, userID int64, accountID string, enabled bool) (SettingsResult, error) {
return s.UpdateSettings(ctx, SettingsUpdateInput{UserID: userID, AccountID: accountID, AutoConfirm: &enabled})
}
// SetRemark 更新账号备注。
func (s *SettingsService) SetRemark(ctx context.Context, userID int64, accountID, remark string) (SettingsResult, error) {
return s.UpdateSettings(ctx, SettingsUpdateInput{UserID: userID, AccountID: accountID, Remark: &remark})
}
// SetPause 更新账号暂停时长;零值会立即唤醒待执行任务。
func (s *SettingsService) SetPause(ctx context.Context, userID int64, accountID string, duration int) (SettingsResult, error) {
if s == nil || s.repository == nil {
return SettingsResult{}, errors.New("账号设置服务未初始化")
}
if accountID == "" {
return SettingsResult{}, errors.New("缺少账号 ID")
}
// pausedUntil、pauseErr 保存暂停写入返回的截止时间和错误。
pausedUntil, pauseErr := s.repository.SetPauseOwned(ctx, userID, accountID, duration)
return SettingsResult{PausedUntil: pausedUntil}, pauseErr
}
// GetPause 查询账号暂停配置及当前暂停状态。
func (s *SettingsService) GetPause(ctx context.Context, userID int64, accountID string) (PauseState, error) {
if s == nil || s.repository == nil {
return PauseState{}, errors.New("账号设置服务未初始化")
}
if accountID == "" {
return PauseState{}, errors.New("缺少账号 ID")
}
return s.repository.GetPauseOwned(ctx, userID, accountID)
}
@@ -0,0 +1,176 @@
package account
import (
"context"
"errors"
"testing"
)
// fakeSettingsRepository 记录账号设置应用服务对持久化端口的调用。
type fakeSettingsRepository struct {
// updateResult 是账号设置写入后返回的暂停截止时间。
updateResult int64
// updateErr 是账号设置写入错误。
updateErr error
// status 是账号当前是否启用。
status bool
// statusErr 是账号状态查询错误。
statusErr error
// lockCalls 是凭证锁获取次数。
lockCalls int
// unlockCalls 是凭证锁释放次数。
unlockCalls int
// statusWrites 是状态写入次数。
statusWrites int
// clearTokensErr 是清理旧连接凭证时返回的预置错误。
clearTokensErr error
}
// LockCredentials 记录凭证锁的获取和释放。
func (f *fakeSettingsRepository) LockCredentials(string) func() {
f.lockCalls++
return func() { f.unlockCalls++ }
}
// UpdateSettings 返回预置的账号设置写入结果。
func (f *fakeSettingsRepository) UpdateSettings(context.Context, SettingsUpdateInput) (int64, error) {
return f.updateResult, f.updateErr
}
// UpdateLoginInfo 模拟登录信息保存成功。
func (f *fakeSettingsRepository) UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error {
return nil
}
// SetStatusOwned 记录状态写入并返回预置错误。
func (f *fakeSettingsRepository) SetStatusOwned(context.Context, int64, string, bool, string) error {
f.statusWrites++
return nil
}
// StatusOwned 返回预置的账号启用状态。
func (f *fakeSettingsRepository) StatusOwned(context.Context, int64, string) (bool, error) {
return f.status, f.statusErr
}
// SetPauseOwned 返回预置的暂停截止时间。
func (f *fakeSettingsRepository) SetPauseOwned(context.Context, int64, string, int) (int64, error) {
return f.updateResult, nil
}
// GetPauseOwned 返回未暂停的默认状态。
func (f *fakeSettingsRepository) GetPauseOwned(context.Context, int64, string) (PauseState, error) {
return PauseState{}, nil
}
// ClearTokens 模拟 Cookie 更新后清理旧连接凭证。
func (f *fakeSettingsRepository) ClearTokens(context.Context, string) error { return f.clearTokensErr }
// fakeSettingsRuntime 记录账号运行实例控制调用。
type fakeSettingsRuntime struct {
// restartCalls 是运行实例重启次数。
restartCalls int
// stopCalls 是运行实例停止次数。
stopCalls int
// restartErr 是预置的重启错误。
restartErr error
}
// Restart 记录重启并返回预置错误。
func (f *fakeSettingsRuntime) Restart(context.Context, string) error {
f.restartCalls++
return f.restartErr
}
// Stop 记录运行实例停止。
func (f *fakeSettingsRuntime) Stop(string) { f.stopCalls++ }
// TestSettingsServiceRestartsAfterCookieWrite 验证 Cookie 写入释放凭证锁后才重启运行实例。
func TestSettingsServiceRestartsAfterCookieWrite(t *testing.T) {
// repository 保存当前测试的伪持久化端口。
repository := &fakeSettingsRepository{updateResult: 123, status: true}
// runtime 保存当前测试的伪运行时端口。
runtime := &fakeSettingsRuntime{}
// service 保存待验证的账号设置应用服务。
// service、err 保存账号设置应用服务及其装配错误。
service, err := NewSettingsService(repository, runtime)
if err != nil {
t.Fatalf("NewSettingsService: %v", err)
}
// cookie 保存本次模拟写入的明文 Cookie,仅存在测试输入作用域。
cookie := "cookie"
// result、err 保存 Cookie 设置后的运行时结果和用例错误。
result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie})
if err != nil || result.PausedUntil != 123 || runtime.restartCalls != 1 {
t.Fatalf("UpdateSettings result=%+v err=%v restart=%d", result, err, runtime.restartCalls)
}
if repository.lockCalls != 1 || repository.unlockCalls != 1 {
t.Fatalf("credential lock calls=%d/%d", repository.lockCalls, repository.unlockCalls)
}
}
// TestSettingsServiceKeepsPersistenceSuccessOnRuntimeFailure 验证运行时重启失败不会伪装成数据库写入失败。
func TestSettingsServiceKeepsPersistenceSuccessOnRuntimeFailure(t *testing.T) {
// repository 保存启用账号的伪持久化端口。
repository := &fakeSettingsRepository{status: true}
// runtime 保存返回重启错误的伪运行时端口。
runtime := &fakeSettingsRuntime{restartErr: errors.New("restart failed")}
// service 保存待验证的账号设置应用服务。
// service、err 保存账号设置应用服务及其装配错误。
service, err := NewSettingsService(repository, runtime)
if err != nil {
t.Fatalf("NewSettingsService: %v", err)
}
// cookie 保存本次模拟写入的明文 Cookie。
cookie := "cookie"
// result、err 保存重启失败时的三态结果和用例错误。
result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie})
if err != nil || result.RuntimeError == nil {
t.Fatalf("UpdateSettings result=%+v err=%v", result, err)
}
}
// TestSettingsServiceContinuesRuntimeAfterTokenCleanupFailure 验证旧 Token 清理失败不会阻止 Cookie 写入后的运行时重启。
func TestSettingsServiceContinuesRuntimeAfterTokenCleanupFailure(t *testing.T) {
// repository 保存 Cookie 写入成功但 Token 清理失败的伪持久化端口。
repository := &fakeSettingsRepository{status: true, clearTokensErr: errors.New("token cleanup failed")}
// runtime 保存运行实例重启调用记录。
runtime := &fakeSettingsRuntime{}
// service、err 保存账号设置应用服务及其装配错误。
service, err := NewSettingsService(repository, runtime)
if err != nil {
t.Fatalf("NewSettingsService: %v", err)
}
// cookie 保存本次模拟写入的 Cookie 输入。
cookie := "cookie"
// result、err 保存 Token 清理失败时的三态结果和用例错误。
result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie})
if err != nil || result.TokenCleanupError == nil || runtime.restartCalls != 1 {
t.Fatalf("UpdateSettings result=%+v err=%v restart=%d", result, err, runtime.restartCalls)
}
}
// TestSettingsServiceStatusControlsRuntime 验证启停状态写入后分别控制运行实例。
func TestSettingsServiceStatusControlsRuntime(t *testing.T) {
// repository 保存状态写入调用记录。
repository := &fakeSettingsRepository{}
// runtime 保存运行实例控制调用记录。
runtime := &fakeSettingsRuntime{}
// service 保存待验证的账号设置应用服务。
// service、err 保存账号设置应用服务及其装配错误。
service, err := NewSettingsService(repository, runtime)
if err != nil {
t.Fatalf("NewSettingsService: %v", err)
}
// err 保存启用账号并重启运行实例的用例错误。
if _, err := service.SetStatus(context.Background(), 7, "a1", true); err != nil || runtime.restartCalls != 1 {
t.Fatalf("enable err=%v restart=%d", err, runtime.restartCalls)
}
// err 保存停用账号并停止运行实例的用例错误。
if _, err := service.SetStatus(context.Background(), 7, "a1", false); err != nil || runtime.stopCalls != 1 {
t.Fatalf("disable err=%v stop=%d", err, runtime.stopCalls)
}
if repository.statusWrites != 2 {
t.Fatalf("status writes=%d", repository.statusWrites)
}
}
@@ -0,0 +1,200 @@
package account
import (
"context"
"errors"
)
// AccountSummary 是账号列表与所有权用例使用的非敏感账号摘要,不包含 Cookie、密码或加密 metadata。
type AccountSummary struct {
// ID 是闲鱼账号的稳定标识。
ID string
// UserID 是账号所属的本地用户标识。
UserID int64
// AutoConfirm 表示账号是否启用自动确认收货。
AutoConfirm bool
// Remark 是用户为账号设置的备注。
Remark string
// PauseDuration 是账号暂停时长,单位为分钟。
PauseDuration int
// PausedUntil 是暂停结束时间的 Unix 秒;零表示当前没有暂停截止时间。
PausedUntil int64
// Username 是账号关联的登录用户名,不包含登录密码。
Username string
// ShowBrowser 表示密码登录流程是否允许显示浏览器。
ShowBrowser bool
// Nickname 是平台账号昵称缓存。
Nickname string
// AvatarURL 是平台账号头像缓存地址。
AvatarURL string
// LastRefreshAt 是最近一次资料刷新时间的 Unix 秒。
LastRefreshAt int64
// LoginMethod 是最近一次成功登录方式。
LoginMethod string
// LastLoginAt 是最近一次成功登录时间的 Unix 秒。
LastLoginAt int64
// CreatedAt 是账号记录创建时间的数据库字符串。
CreatedAt string
}
// AdminAccountSummary 是管理员账号列表使用的非敏感摘要。
type AdminAccountSummary struct {
// ID 是闲鱼账号的稳定标识。
ID string
// UserID 是账号所属的本地用户标识。
UserID int64
// Remark 是用户为账号设置的备注。
Remark string
// CreatedAt 是账号记录创建时间的数据库字符串。
CreatedAt string
// Owner 是账号所属用户的展示名。
Owner string
// Enabled 表示账号当前是否启用。
Enabled bool
}
// AccountSummaryRepository 定义账号摘要和所有权用例需要的最小持久化端口。
type AccountSummaryRepository interface {
// ListOwnedIDs 返回指定用户拥有的账号 ID,不读取凭证字段。
ListOwnedIDs(context.Context, int64) ([]string, error)
// ListSummaries 返回指定用户的非敏感账号摘要列表。
ListSummaries(context.Context, int64) ([]AccountSummary, error)
// GetOwnedSummary 返回指定用户拥有的单个非敏感账号摘要。
GetOwnedSummary(context.Context, int64, string) (AccountSummary, error)
// ExistsOwned 判断账号是否属于指定用户,仅返回存在性结论。
ExistsOwned(context.Context, int64, string) (bool, error)
// GetOwnerID 返回指定账号所属用户标识,不读取凭证字段。
GetOwnerID(context.Context, string) (int64, error)
// StatusOwned 返回指定用户账号的启用状态,并在读取前复核归属。
StatusOwned(context.Context, int64, string) (bool, error)
}
// AdminSummaryRepository 定义管理员读取全局账号摘要所需的最小持久化端口。
type AdminSummaryRepository interface {
// ListAdminSummaries 返回所有账号的非敏感管理员摘要。
ListAdminSummaries(context.Context) ([]AdminAccountSummary, error)
}
// SummaryService 编排账号摘要读取、所有权判断和管理员账号列表,不依赖 HTTP 或数据库模型。
type SummaryService struct {
// repository 保存普通用户账号摘要与所有权查询端口。
repository AccountSummaryRepository
// adminRepository 保存管理员全局账号摘要查询端口。
adminRepository AdminSummaryRepository
}
// NewSummaryService 构造账号摘要应用服务并校验普通用户查询端口。
func NewSummaryService(repository AccountSummaryRepository, adminRepository AdminSummaryRepository) (*SummaryService, error) {
if repository == nil {
return nil, errors.New("账号摘要 repository 未初始化")
}
return &SummaryService{repository: repository, adminRepository: adminRepository}, nil
}
// ListOwnedIDs 返回指定用户拥有的账号 ID;数据库适配器错误原样向上返回。
func (s *SummaryService) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) {
// validationErr 表示当前用户身份或摘要服务状态无效。
validationErr := s.validateUser(userID)
if validationErr != nil {
return nil, validationErr
}
return s.repository.ListOwnedIDs(ctx, userID)
}
// ListSummaries 返回指定用户的非敏感账号摘要列表。
func (s *SummaryService) ListSummaries(ctx context.Context, userID int64) ([]AccountSummary, error) {
// validationErr 表示当前用户身份或摘要服务状态无效。
validationErr := s.validateUser(userID)
if validationErr != nil {
return nil, validationErr
}
return s.repository.ListSummaries(ctx, userID)
}
// GetOwnedSummary 返回指定用户拥有的单个账号摘要;不会读取或解密凭证。
func (s *SummaryService) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (AccountSummary, error) {
// validationErr 表示账号摘要请求的用户或账号标识无效。
validationErr := s.validateRequest(userID, accountID)
if validationErr != nil {
return AccountSummary{}, validationErr
}
return s.repository.GetOwnedSummary(ctx, userID, accountID)
}
// ExistsOwned 返回账号是否属于指定用户;查询只返回存在性结论,不读取或解密凭证。
func (s *SummaryService) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
// validationErr 表示账号归属请求的用户或账号标识无效。
validationErr := s.validateRequest(userID, accountID)
if validationErr != nil {
return false, validationErr
}
return s.repository.ExistsOwned(ctx, userID, accountID)
}
// StatusOwned 返回指定用户账号的启用状态;归属和数据库错误均向上返回。
func (s *SummaryService) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) {
// validationErr 表示账号状态请求的用户或账号标识无效。
validationErr := s.validateRequest(userID, accountID)
if validationErr != nil {
return false, validationErr
}
return s.repository.StatusOwned(ctx, userID, accountID)
}
// RequireOwnership 校验账号是否属于用户,并区分账号不存在、越权和基础设施故障。
func (s *SummaryService) RequireOwnership(ctx context.Context, userID int64, accountID string) error {
// validationErr 表示账号所有权请求的用户或账号标识无效。
validationErr := s.validateRequest(userID, accountID)
if validationErr != nil {
return validationErr
}
// owned、queryErr 保存联合所有权查询结果及其基础设施错误。
owned, queryErr := s.repository.ExistsOwned(ctx, userID, accountID)
if queryErr != nil {
return queryErr
}
if owned {
return nil
}
// ownerID、ownerErr 用于区分账号不存在和账号属于其他用户。
ownerID, ownerErr := s.repository.GetOwnerID(ctx, accountID)
if ownerErr != nil {
return ownerErr
}
if ownerID != userID {
return ErrForbidden
}
return ErrNotFound
}
// ListAdminSummaries 返回管理员账号摘要;管理员端口未装配时明确失败。
func (s *SummaryService) ListAdminSummaries(ctx context.Context) ([]AdminAccountSummary, error) {
if s == nil || s.adminRepository == nil {
return nil, errors.New("管理员账号摘要 repository 未初始化")
}
return s.adminRepository.ListAdminSummaries(ctx)
}
// validateUser 校验所有权查询必须使用真实用户身份,拒绝管理员隐式用户零值。
func (s *SummaryService) validateUser(userID int64) error {
if s == nil || s.repository == nil {
return errors.New("账号摘要服务未初始化")
}
if userID <= 0 {
return errors.New("账号用户身份无效")
}
return nil
}
// validateRequest 校验账号摘要查询的用户身份和账号标识。
func (s *SummaryService) validateRequest(userID int64, accountID string) error {
// validationErr 表示账号摘要请求的用户身份无效。
validationErr := s.validateUser(userID)
if validationErr != nil {
return validationErr
}
if accountID == "" {
return errors.New("缺少账号 ID")
}
return nil
}
@@ -0,0 +1,174 @@
package account
import (
"context"
"errors"
"testing"
)
// summaryRepositoryFake 是账号摘要应用服务测试用的可控持久化端口替身。
type summaryRepositoryFake struct {
// ids 是待返回的账号 ID 列表。
ids []string
// summaries 是待返回的普通用户账号摘要。
summaries []AccountSummary
// adminSummaries 是待返回的管理员账号摘要。
adminSummaries []AdminAccountSummary
// summary 是待返回的单个账号摘要。
summary AccountSummary
// ownerID 是待返回的账号所有者。
ownerID int64
// owned 是待返回的联合所有权结论。
owned bool
// listErr、summaryErr、ownedErr、ownerErr、statusErr 模拟各查询阶段错误。
listErr error
summaryErr error
ownedErr error
ownerErr error
statusErr error
// enabled 是待返回的账号启用状态。
enabled bool
}
// ListOwnedIDs 返回测试预置的账号 ID 列表或列表错误。
func (f *summaryRepositoryFake) ListOwnedIDs(context.Context, int64) ([]string, error) {
return f.ids, f.listErr
}
// ListSummaries 返回测试预置的账号摘要或列表错误。
func (f *summaryRepositoryFake) ListSummaries(context.Context, int64) ([]AccountSummary, error) {
return f.summaries, f.listErr
}
// GetOwnedSummary 返回测试预置的账号摘要或摘要错误。
func (f *summaryRepositoryFake) GetOwnedSummary(context.Context, int64, string) (AccountSummary, error) {
return f.summary, f.summaryErr
}
// ExistsOwned 返回测试预置的所有权结论或查询错误。
func (f *summaryRepositoryFake) ExistsOwned(context.Context, int64, string) (bool, error) {
return f.owned, f.ownedErr
}
// GetOwnerID 返回测试预置的账号所有者或查询错误。
func (f *summaryRepositoryFake) GetOwnerID(context.Context, string) (int64, error) {
return f.ownerID, f.ownerErr
}
// StatusOwned 返回测试预置的启用状态或查询错误。
func (f *summaryRepositoryFake) StatusOwned(context.Context, int64, string) (bool, error) {
return f.enabled, f.statusErr
}
// ListAdminSummaries 返回测试预置的管理员账号摘要或查询错误。
func (f *summaryRepositoryFake) ListAdminSummaries(context.Context) ([]AdminAccountSummary, error) {
return f.adminSummaries, f.listErr
}
// TestSummaryServiceValidatesInputs 验证账号摘要服务拒绝无效用户和空账号标识。
func TestSummaryServiceValidatesInputs(t *testing.T) {
// service 是使用可控摘要端口构造的应用服务。
service, err := NewSummaryService(&summaryRepositoryFake{}, &summaryRepositoryFake{})
if err != nil {
t.Fatalf("构造摘要服务失败: %v", err)
}
// _, listErr 保存无效用户列表查询的验证错误。
if _, listErr := service.ListOwnedIDs(context.Background(), 0); listErr == nil {
t.Fatal("无效用户 ID 不应读取账号列表")
}
// _, summaryErr 保存空账号摘要查询的验证错误。
if _, summaryErr := service.GetOwnedSummary(context.Background(), 7, ""); summaryErr == nil {
t.Fatal("空账号 ID 不应读取账号摘要")
}
}
// TestSummaryServicePropagatesReadAndAdminErrors 验证摘要服务不吞掉各读取阶段错误。
func TestSummaryServicePropagatesReadAndAdminErrors(t *testing.T) {
// readErr 是底层摘要查询模拟的基础设施故障。
readErr := errors.New("摘要读取失败")
// repository 是返回读取故障的摘要端口替身。
repository := &summaryRepositoryFake{listErr: readErr, summaryErr: readErr, ownedErr: readErr, statusErr: readErr}
// service 是绑定故障端口的应用服务。
service, err := NewSummaryService(repository, repository)
if err != nil {
t.Fatalf("构造摘要服务失败: %v", err)
}
// _, listErr 保存摘要列表读取的底层错误。
if _, listErr := service.ListSummaries(context.Background(), 7); !errors.Is(listErr, readErr) {
t.Fatalf("列表错误未保留: %v", listErr)
}
// _, summaryErr 保存单个账号摘要读取的底层错误。
if _, summaryErr := service.GetOwnedSummary(context.Background(), 7, "acc1"); !errors.Is(summaryErr, readErr) {
t.Fatalf("单项摘要错误未保留: %v", summaryErr)
}
// _, ownedErr 保存账号归属查询的底层错误。
if _, ownedErr := service.ExistsOwned(context.Background(), 7, "acc1"); !errors.Is(ownedErr, readErr) {
t.Fatalf("归属错误未保留: %v", ownedErr)
}
// _, statusErr 保存账号状态读取的底层错误。
if _, statusErr := service.StatusOwned(context.Background(), 7, "acc1"); !errors.Is(statusErr, readErr) {
t.Fatalf("状态错误未保留: %v", statusErr)
}
// _, adminErr 保存管理员摘要读取的底层错误。
if _, adminErr := service.ListAdminSummaries(context.Background()); !errors.Is(adminErr, readErr) {
t.Fatalf("管理员摘要错误未保留: %v", adminErr)
}
}
// TestSummaryServiceRequireOwnershipDistinguishesResults 验证所有权服务区分本人、越权、不存在和查询故障。
func TestSummaryServiceRequireOwnershipDistinguishesResults(t *testing.T) {
// cases 覆盖所有权判断的四种结果,并确保越权不会读取敏感数据。
cases := []struct {
// name 是当前所有权场景名称。
name string
// repository 是当前场景使用的摘要端口替身。
repository *summaryRepositoryFake
// wantErr 是期望的稳定应用错误;nil 表示归属通过。
wantErr error
}{
{name: "owned", repository: &summaryRepositoryFake{owned: true}, wantErr: nil},
{name: "forbidden", repository: &summaryRepositoryFake{ownerID: 8}, wantErr: ErrForbidden},
{name: "missing", repository: &summaryRepositoryFake{ownerErr: ErrNotFound}, wantErr: ErrNotFound},
{name: "query-failure", repository: &summaryRepositoryFake{ownedErr: errors.New("exists 查询失败")}, wantErr: errors.New("exists 查询失败")},
}
// testCase 表示当前正在验证的所有权场景。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// service 是当前场景的账号摘要应用服务。
service, err := NewSummaryService(testCase.repository, testCase.repository)
if err != nil {
t.Fatalf("构造摘要服务失败: %v", err)
}
// gotErr 保存应用服务返回的所有权结果。
gotErr := service.RequireOwnership(context.Background(), 7, "acc1")
if testCase.wantErr == nil {
if gotErr != nil {
t.Fatalf("本人账号不应失败: %v", gotErr)
}
return
}
if gotErr == nil || gotErr.Error() != testCase.wantErr.Error() {
t.Fatalf("所有权错误=%v,期望=%v", gotErr, testCase.wantErr)
}
})
}
}
// TestNewSummaryServiceRequiresRepository 验证摘要服务拒绝缺失普通用户端口,但允许管理员端口按需缺省。
func TestNewSummaryServiceRequiresRepository(t *testing.T) {
// adminRepository 是满足管理员摘要能力的测试端口。
adminRepository := &summaryRepositoryFake{}
// _, missingRepositoryErr 保存缺少普通用户端口时的构造错误。
if _, missingRepositoryErr := NewSummaryService(nil, adminRepository); missingRepositoryErr == nil {
t.Fatal("缺少普通用户摘要端口时应构造失败")
}
// service 是仅装配普通用户端口的应用服务。
service, err := NewSummaryService(adminRepository, nil)
if err != nil {
t.Fatalf("管理员端口可选时构造失败: %v", err)
}
// _, missingAdminErr 保存缺少管理员端口时的调用错误。
if _, missingAdminErr := service.ListAdminSummaries(context.Background()); missingAdminErr == nil {
t.Fatal("未装配管理员端口时不应伪装成功")
}
}
+98
View File
@@ -0,0 +1,98 @@
// Package admin 提供管理员用户与全局统计的应用用例,不依赖 HTTP 或数据库模型。
package admin
import (
"context"
"errors"
)
// ErrInvalidUser 表示请求没有提供有效的管理员身份。
var ErrInvalidUser = errors.New("管理员身份无效")
// ErrSelfDelete 表示管理员试图删除当前会话对应的用户。
var ErrSelfDelete = errors.New("不能删除当前登录用户")
// UserSummary 是管理员用户列表使用的非敏感摘要。
type UserSummary struct {
// ID 是用户稳定标识。
ID int64
// Username 是用户登录名。
Username string
// Email 是用户联系邮箱。
Email string
// IsActive 表示用户是否启用。
IsActive bool
// IsAdmin 表示用户是否拥有管理员权限。
IsAdmin bool
// CreatedAt 是用户创建时间文本。
CreatedAt string
// CookieCount 是用户拥有的账号数量。
CookieCount int
}
// Stats 是管理员仪表盘的全局聚合结果。
type Stats struct {
// TotalUsers 是用户总数。
TotalUsers int64
// TotalCookies 是账号总数。
TotalCookies int64
// ActiveCookies 是启用账号总数。
ActiveCookies int64
// TotalCards 是卡券组总数。
TotalCards int64
// TotalKeywords 是关键词规则总数。
TotalKeywords int64
// TotalOrders 是未删除订单总数。
TotalOrders int64
}
// Repository 定义管理员用例需要的最小持久化能力。
type Repository interface {
// ListUsers 返回不包含密码和凭证的用户摘要。
ListUsers(context.Context) ([]UserSummary, error)
// DeleteUser 删除用户及其由数据库层管理的关联资源。
DeleteUser(context.Context, int64) error
// Stats 返回管理员仪表盘聚合计数。
Stats(context.Context) (Stats, error)
}
// Service 编排管理员用户管理和仪表盘查询。
type Service struct {
// repository 保存管理员用例的窄持久化端口。
repository Repository
}
// NewService 构造管理员应用服务。
func NewService(repository Repository) *Service {
return &Service{repository: repository}
}
// ListUsers 查询管理员用户摘要。
func (s *Service) ListUsers(ctx context.Context) ([]UserSummary, error) {
if s == nil || s.repository == nil {
return nil, errors.New("管理员服务未初始化")
}
return s.repository.ListUsers(ctx)
}
// DeleteUser 删除目标用户;服务层拒绝删除当前会话用户,避免 HTTP 层重复实现规则。
func (s *Service) DeleteUser(ctx context.Context, currentUserID, targetUserID int64) error {
if currentUserID <= 0 || targetUserID <= 0 {
return ErrInvalidUser
}
if currentUserID == targetUserID {
return ErrSelfDelete
}
if s == nil || s.repository == nil {
return errors.New("管理员服务未初始化")
}
return s.repository.DeleteUser(ctx, targetUserID)
}
// Stats 查询管理员仪表盘统计。
func (s *Service) Stats(ctx context.Context) (Stats, error) {
if s == nil || s.repository == nil {
return Stats{}, errors.New("管理员服务未初始化")
}
return s.repository.Stats(ctx)
}
+117
View File
@@ -0,0 +1,117 @@
package admin
import (
"context"
"errors"
"testing"
)
// adminRepositoryStub 保存管理员应用服务测试中的可控仓储行为和调用记录。
type adminRepositoryStub struct {
// listResult 保存用户列表返回值。
listResult []UserSummary
// listErr 保存用户列表错误。
listErr error
// deleteErr 保存用户删除错误。
deleteErr error
// statsResult 保存统计返回值。
statsResult Stats
// statsErr 保存统计错误。
statsErr error
// deletedUserID 保存最后一次删除的目标用户。
deletedUserID int64
}
// ListUsers 返回测试预置的用户摘要。
func (r *adminRepositoryStub) ListUsers(context.Context) ([]UserSummary, error) {
return r.listResult, r.listErr
}
// DeleteUser 记录删除目标并返回测试预置错误。
func (r *adminRepositoryStub) DeleteUser(_ context.Context, userID int64) error {
r.deletedUserID = userID
return r.deleteErr
}
// Stats 返回测试预置的仪表盘统计。
func (r *adminRepositoryStub) Stats(context.Context) (Stats, error) {
return r.statsResult, r.statsErr
}
// TestServiceListUsersAndStats 验证管理员摘要与统计成功、错误和空服务分支。
func TestServiceListUsersAndStats(t *testing.T) {
// expectedUsers、expectedStats 保存成功路径的应用模型结果。
expectedUsers := []UserSummary{{ID: 7, Username: "admin"}}
// expectedStats 保存成功路径的统计应用模型结果。
expectedStats := Stats{TotalUsers: 2, TotalOrders: 3}
// repository 保存成功路径测试仓储。
repository := &adminRepositoryStub{listResult: expectedUsers, statsResult: expectedStats}
// service 保存待验证的管理员应用服务。
service := NewService(repository)
// users、usersErr 保存用户摘要查询结果。
users, usersErr := service.ListUsers(context.Background())
if usersErr != nil || len(users) != 1 || users[0].ID != 7 {
t.Fatalf("用户摘要查询异常 users=%v err=%v", users, usersErr)
}
// stats、statsErr 保存统计查询结果。
stats, statsErr := service.Stats(context.Background())
if statsErr != nil || stats.TotalOrders != 3 {
t.Fatalf("统计查询异常 stats=%+v err=%v", stats, statsErr)
}
// listFailure、statsFailure 保存基础设施错误分支。
listFailure := errors.New("list failed")
// statsFailure、failureService 保存统计错误和组合错误仓储服务。
statsFailure := errors.New("stats failed")
// failureService 保存返回基础设施错误的管理员应用服务。
failureService := NewService(&adminRepositoryStub{listErr: listFailure, statsErr: statsFailure})
if !errors.Is(mustListUsers(failureService), listFailure) || !errors.Is(mustStats(failureService), statsFailure) {
t.Fatal("管理员查询错误未原样返回")
}
// err 保存空管理员服务的装配错误。
if _, err := (*Service)(nil).ListUsers(context.Background()); err == nil {
t.Fatal("空管理员服务应拒绝用户列表查询")
}
}
// mustListUsers 将列表错误转换为便于测试断言的 error。
func mustListUsers(service *Service) error {
// err 保存管理员列表查询错误。
_, err := service.ListUsers(context.Background())
return err
}
// mustStats 将统计错误转换为便于测试断言的 error。
func mustStats(service *Service) error {
// err 保存管理员统计查询错误。
_, err := service.Stats(context.Background())
return err
}
// TestServiceDeleteUser 验证无效身份、自删、成功删除和仓储失败分支。
func TestServiceDeleteUser(t *testing.T) {
// repository 保存可记录删除调用的测试仓储。
repository := &adminRepositoryStub{}
// service 保存待验证的管理员应用服务。
service := NewService(repository)
if !errors.Is(service.DeleteUser(context.Background(), 0, 2), ErrInvalidUser) {
t.Fatal("无效当前用户应被拒绝")
}
if !errors.Is(service.DeleteUser(context.Background(), 1, 1), ErrSelfDelete) {
t.Fatal("删除当前用户应被拒绝")
}
// err 保存管理员删除操作的错误。
if err := service.DeleteUser(context.Background(), 1, 2); err != nil || repository.deletedUserID != 2 {
t.Fatalf("删除成功路径异常 err=%v id=%d", err, repository.deletedUserID)
}
// deleteFailure 保存仓储删除失败结果。
deleteFailure := errors.New("delete failed")
// err 保存删除仓储返回的错误。
if err := NewService(&adminRepositoryStub{deleteErr: deleteFailure}).DeleteUser(context.Background(), 1, 2); !errors.Is(err, deleteFailure) {
t.Fatal("删除错误未原样返回")
}
// unavailableErr 保存空服务的装配错误。
unavailableErr := (*Service)(nil).DeleteUser(context.Background(), 1, 2)
if unavailableErr == nil {
t.Fatal("空管理员服务应拒绝删除")
}
}
+246
View File
@@ -0,0 +1,246 @@
// Package analytics 定义订单分析用例、纯查询模型和消费者侧持久化 Port。
// 本包不依赖数据库、HTTP、平台协议或 Server 实现。
package analytics
import (
"context"
"time"
)
// Query 是订单分析用例使用的用户范围、日期和时区条件。
type Query struct {
// UserID 是当前登录用户的本地身份标识。
UserID int64
// StartDate 是用户本地日期范围的起始日期,格式为 YYYY-MM-DD。
StartDate string
// EndDate 是用户本地日期范围的结束日期,格式为 YYYY-MM-DD。
EndDate string
// Location 是用于日期边界和按日聚合的用户本地时区。
Location *time.Location
}
// Filter 是持久化查询已经转换后的用户、UTC 日期和有效状态条件。
type Filter struct {
// UserID 是订单所属账号对应的用户身份标识。
UserID int64
// StartAt 是包含边界的 UTC 起始时间文本;为空表示不限制起始时间。
StartAt string
// EndBefore 是排除边界的 UTC 结束时间文本;为空表示不限制结束时间。
EndBefore string
// Statuses 是允许参与统计的订单状态候选集合。
Statuses []string
}
// DashboardStats 是用户仪表盘所需的非敏感统计摘要。
type DashboardStats struct {
// TotalCookies 是用户账号总数。
TotalCookies int64
// ActiveCookies 是没有明确禁用记录的账号数。
ActiveCookies int64
// TotalCards 是用户卡密组总数。
TotalCards int64
// AvailableCardStock 是启用数据卡密组中的非空卡密行数。
AvailableCardStock int64
// TotalKeywords 是用户关键词规则总数。
TotalKeywords int64
// TotalOrders 是用户未删除订单总数。
TotalOrders int64
}
// RevenueStats 是订单收益聚合结果。
type RevenueStats struct {
// TotalOrders 是统计范围内的去重订单数。
TotalOrders int
// TotalAmount 是统计范围内的订单总金额。
TotalAmount float64
// AvgAmount 是统计范围内的订单平均金额。
AvgAmount float64
// UniqueBuyers 是统计范围内的去重买家数。
UniqueBuyers int
// UniqueItems 是统计范围内的去重商品数。
UniqueItems int
}
// DailyRecord 是按订单返回的日期聚合原始记录。
type DailyRecord struct {
// OrderID 是用于保留原有订单计数口径的订单标识。
OrderID string
// Amount 是数据库中的订单金额文本。
Amount string
// CreatedAt 是数据库中的订单创建时间文本。
CreatedAt string
}
// StatusRecord 是数据库按原始状态聚合的结果。
type StatusRecord struct {
// Status 是持久化的订单状态文本或数字码。
Status string
// Count 是该原始状态对应的去重订单数。
Count int
// Amount 是该原始状态对应的金额合计。
Amount float64
}
// CityRecord 是数据库按收货城市聚合的结果。
type CityRecord struct {
// City 是收货城市名称。
City string
// Count 是该城市的去重订单数。
Count int
// Amount 是该城市的金额合计。
Amount float64
}
// ItemRecord 是数据库按商品标识聚合的结果。
type ItemRecord struct {
// ItemID 是平台商品标识。
ItemID string
// Count 是该商品的去重订单数。
Count int
// TotalAmount 是该商品的金额合计。
TotalAmount float64
// AvgAmount 是该商品的平均金额。
AvgAmount float64
}
// ValidOrderRecord 是有效订单明细所需的非敏感字段。
type ValidOrderRecord struct {
// OrderID 是平台订单标识。
OrderID string
// ItemID 是平台商品标识。
ItemID string
// ItemTitle 是本地商品标题。
ItemTitle string
// ItemDetail 是本地商品详情 JSON,用于提取主图地址。
ItemDetail string
// BuyerID 是买家平台标识。
BuyerID string
// Quantity 是订单数量文本。
Quantity string
// Amount 是订单金额文本。
Amount string
// Status 是持久化的订单状态文本或数字码。
Status string
// CookieID 是订单所属账号标识。
CookieID string
// CreatedAt 是订单创建时间文本。
CreatedAt string
}
// OrderAnalytics 是订单分析用例的完整结果模型。
type OrderAnalytics struct {
// RevenueStats 是收益汇总。
RevenueStats RevenueStats
// DailyStats 是按用户本地日期聚合的结果。
DailyStats []DailyStats
// StatusStats 是按归一化订单状态聚合的结果。
StatusStats []StatusStats
// CityStats 是按收货城市聚合的结果。
CityStats []CityStats
// ItemStats 是按商品标识聚合的结果。
ItemStats []ItemStats
}
// DailyStats 是单个本地日期的订单聚合结果。
type DailyStats struct {
// Date 是用户本地日期。
Date string
// OrderCount 是该日期的订单数。
OrderCount int
// Amount 是该日期的金额合计。
Amount float64
}
// StatusStats 是单个归一化状态的订单聚合结果。
type StatusStats struct {
// Status 是归一化后的状态名称。
Status string
// Count 是该状态的订单数。
Count int
// Amount 是该状态的金额合计。
Amount float64
}
// CityStats 是单个收货城市的订单聚合结果。
type CityStats struct {
// City 是收货城市名称。
City string
// OrderCount 是该城市的订单数。
OrderCount int
// TotalAmount 是该城市的金额合计。
TotalAmount float64
}
// ItemStats 是单个商品的订单聚合结果。
type ItemStats struct {
// ItemID 是平台商品标识。
ItemID string
// OrderCount 是该商品的订单数。
OrderCount int
// TotalAmount 是该商品的金额合计。
TotalAmount float64
// AvgAmount 是该商品的平均金额。
AvgAmount float64
}
// ValidOrders 是有效订单分页结果。
type ValidOrders struct {
// Orders 是当前页的有效订单明细。
Orders []ValidOrder
// Total 是筛选条件下的有效订单总数。
Total int
// Page 是当前页码。
Page int
// PageSize 是当前页大小。
PageSize int
// Truncated 表示结果是否还有未返回的订单。
Truncated bool
}
// ValidOrder 是面向 HTTP 映射的有效订单明细模型。
type ValidOrder struct {
// OrderID 是平台订单标识。
OrderID string
// ItemID 是平台商品标识。
ItemID string
// BuyerID 是买家平台标识。
BuyerID string
// ItemTitle 是本地商品标题。
ItemTitle string
// ItemImage 是从商品详情提取的主图地址。
ItemImage string
// Quantity 是订单数量文本。
Quantity string
// Amount 是订单金额文本。
Amount string
// OrderStatus 是兼容字段,值为归一化状态名称。
OrderStatus string
// Status 是归一化状态名称。
Status string
// CookieID 是订单所属账号标识。
CookieID string
// CreatedAt 是订单创建时间文本。
CreatedAt string
}
// Repository 定义订单分析用例需要的最小查询能力。
type Repository interface {
// DashboardStats 返回用户范围内的仪表盘计数。
DashboardStats(ctx context.Context, userID int64) (DashboardStats, error)
// AvailableCardStock 返回用户启用数据卡密组中的可用卡密行数。
AvailableCardStock(ctx context.Context, userID int64) (int64, error)
// QueryRevenue 返回收益汇总。
QueryRevenue(ctx context.Context, filter Filter) (RevenueStats, error)
// QueryDaily 返回订单日期聚合所需的原始记录。
QueryDaily(ctx context.Context, filter Filter) ([]DailyRecord, error)
// QueryStatus 返回订单状态聚合结果。
QueryStatus(ctx context.Context, filter Filter) ([]StatusRecord, error)
// QueryCity 返回收货城市聚合结果。
QueryCity(ctx context.Context, filter Filter) ([]CityRecord, error)
// QueryItem 返回商品聚合结果。
QueryItem(ctx context.Context, filter Filter) ([]ItemRecord, error)
// CountValidOrders 返回有效订单总数。
CountValidOrders(ctx context.Context, filter Filter) (int, error)
// ListValidOrders 返回有效订单分页明细。
ListValidOrders(ctx context.Context, filter Filter, limit, offset int) ([]ValidOrderRecord, error)
}
+375
View File
@@ -0,0 +1,375 @@
package analytics
import (
"context"
"encoding/json"
"errors"
"sort"
"strconv"
"strings"
"time"
)
// ValidOrderStatuses 是参与订单分析的有效状态候选集合。
var ValidOrderStatuses = []string{"pending_ship", "paid", "2", "shipped", "3", "completed", "4", "11"}
// Stage 标识订单分析失败的查询阶段。
type Stage string
const (
// StageRevenue 表示收益汇总查询失败。
StageRevenue Stage = "revenue"
// StageDaily 表示每日统计查询失败。
StageDaily Stage = "daily"
// StageStatus 表示状态统计查询失败。
StageStatus Stage = "status"
// StageCity 表示城市统计查询失败。
StageCity Stage = "city"
// StageItem 表示商品统计查询失败。
StageItem Stage = "item"
// StageValidCount 表示有效订单总数查询失败。
StageValidCount Stage = "valid_count"
// StageValidRows 表示有效订单明细查询失败。
StageValidRows Stage = "valid_rows"
)
// StageError 保留查询阶段并包装底层错误,供传输层映射兼容消息。
type StageError struct {
// Stage 是失败的查询阶段。
Stage Stage
// Err 是底层查询错误。
Err error
}
// Error 返回底层错误文本。
func (e *StageError) Error() string {
if e == nil || e.Err == nil {
return "订单分析查询失败"
}
return e.Err.Error()
}
// Unwrap 暴露底层查询错误以支持 errors.Is 和 errors.As。
func (e *StageError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
// NewService 构造订单分析应用服务。
func NewService(repository Repository) *Service {
return &Service{repository: repository}
}
// Service 编排订单分析用例,不感知 HTTP、数据库连接或 Server。
type Service struct {
// repository 提供订单分析所需的窄查询能力。
repository Repository
}
// LocationFromOffset 将浏览器提交的分钟偏移转换为用户时区。
func LocationFromOffset(rawOffset string) *time.Location {
// offset 是浏览器相对 UTC 的分钟偏移。
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)
}
// DateBoundary 将用户本地日期转换为数据库使用的 UTC 边界文本。
func DateBoundary(raw string, endExclusive bool, location *time.Location) string {
if location == nil {
location = time.Local
}
// parsed 是按用户时区解释后的日期起点。
parsed, err := time.ParseInLocation("2006-01-02", strings.TrimSpace(raw), location)
if err != nil {
return raw
}
if endExclusive {
parsed = parsed.AddDate(0, 0, 1)
}
return parsed.UTC().Format("2006-01-02 15:04:05")
}
// DashboardStats 查询用户数据概览和可用卡密库存。
func (svc *Service) DashboardStats(ctx context.Context, userID int64) (DashboardStats, error) {
// stats 是数据库返回的用户范围计数。
stats, err := svc.repository.DashboardStats(ctx, userID)
if err != nil {
return DashboardStats{}, err
}
// stock 是基础设施按数据卡密组内容计算出的可用库存数量。
stock, err := svc.repository.AvailableCardStock(ctx, userID)
if err != nil {
return DashboardStats{}, err
}
stats.AvailableCardStock = stock
return stats, nil
}
// OrderAnalytics 查询收益及按日、状态、城市和商品维度聚合的订单分析结果。
func (svc *Service) OrderAnalytics(ctx context.Context, query Query) (OrderAnalytics, error) {
// filter 是按用户本地日期转换后的持久化查询条件。
filter := query.filter()
// revenue 是收益汇总查询结果。
revenue, err := svc.repository.QueryRevenue(ctx, filter)
if err != nil {
return OrderAnalytics{}, &StageError{Stage: StageRevenue, Err: err}
}
// dailyRecords 是按订单返回的日期聚合原始记录。
dailyRecords, err := svc.repository.QueryDaily(ctx, filter)
if err != nil {
return OrderAnalytics{}, &StageError{Stage: StageDaily, Err: err}
}
// dailyMap 按用户本地日期累计订单数量和金额。
dailyMap := make(map[string]dailyValue)
// record 是当前订单日期聚合原始记录。
for _, record := range dailyRecords {
// created 是解析后的订单创建时间。
created := parseDBTime(record.CreatedAt)
if created.IsZero() {
continue
}
if query.Location != nil {
created = created.In(query.Location)
}
// date 是订单在用户时区中的日期。
date := created.Format("2006-01-02")
// value 是当前日期的累计统计值。
value := dailyMap[date]
value.count++
value.amount += parseAmount(record.Amount)
dailyMap[date] = value
}
// daily 是排序后的按日统计结果。
daily := make([]DailyStats, 0, len(dailyMap))
// 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, DailyStats{Date: date, OrderCount: value.count, Amount: round2(value.amount)})
}
// statusRecords 是数据库按原始状态返回的聚合结果。
statusRecords, err := svc.repository.QueryStatus(ctx, filter)
if err != nil {
return OrderAnalytics{}, &StageError{Stage: StageStatus, Err: err}
}
// statusMap 按归一化状态累计数据库聚合结果。
statusMap := make(map[string]statusValue)
// record 是当前原始状态聚合记录。
for _, record := range statusRecords {
// status 是兼容数字码转换后的状态名称。
status := normalizeStatus(record.Status)
// value 是当前状态的累计统计值。
value := statusMap[status]
value.count += record.Count
value.amount += record.Amount
statusMap[status] = value
}
// statusStats 是按订单数量降序排列的状态统计结果。
statusStats := make([]StatusStats, 0, len(statusMap))
// 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, StatusStats{Status: status, Count: value.count, Amount: round2(value.amount)})
}
// cityRecords 是数据库按收货城市返回的聚合结果。
cityRecords, err := svc.repository.QueryCity(ctx, filter)
if err != nil {
return OrderAnalytics{}, &StageError{Stage: StageCity, Err: err}
}
// cityStats 是收货城市统计结果。
cityStats := make([]CityStats, 0, len(cityRecords))
// record 是当前收货城市聚合记录。
for _, record := range cityRecords {
cityStats = append(cityStats, CityStats{City: record.City, OrderCount: record.Count, TotalAmount: round2(record.Amount)})
}
// itemRecords 是数据库按商品返回的聚合结果。
itemRecords, err := svc.repository.QueryItem(ctx, filter)
if err != nil {
return OrderAnalytics{}, &StageError{Stage: StageItem, Err: err}
}
// itemStats 是商品排行统计结果。
itemStats := make([]ItemStats, 0, len(itemRecords))
// record 是当前商品聚合记录。
for _, record := range itemRecords {
itemStats = append(itemStats, ItemStats{ItemID: record.ItemID, OrderCount: record.Count, TotalAmount: round2(record.TotalAmount), AvgAmount: round2(record.AvgAmount)})
}
return OrderAnalytics{RevenueStats: RevenueStats{
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 *Service) ValidOrders(ctx context.Context, query Query, page, pageSize int) (ValidOrders, error) {
// filter 是按用户本地日期转换后的持久化查询条件。
filter := query.filter()
// total 是符合筛选条件的有效订单总数。
total, err := svc.repository.CountValidOrders(ctx, filter)
if err != nil {
return ValidOrders{}, &StageError{Stage: StageValidCount, Err: err}
}
// offset 是当前分页需要跳过的记录数。
offset := (page - 1) * pageSize
// records 是当前分页的订单明细原始记录。
records, err := svc.repository.ListValidOrders(ctx, filter, pageSize, offset)
if err != nil {
return ValidOrders{}, &StageError{Stage: StageValidRows, Err: err}
}
// orders 是面向传输层的有效订单明细。
orders := make([]ValidOrder, 0, len(records))
// record 是当前有效订单原始记录。
for _, record := range records {
// status 是兼容数字码转换后的状态名称。
status := normalizeStatus(record.Status)
orders = append(orders, ValidOrder{
OrderID: record.OrderID, ItemID: record.ItemID, BuyerID: record.BuyerID, ItemTitle: record.ItemTitle,
ItemImage: itemImageFromDetail(record.ItemDetail), Quantity: record.Quantity, Amount: record.Amount,
OrderStatus: status, Status: status, CookieID: record.CookieID, CreatedAt: record.CreatedAt,
})
}
return ValidOrders{Orders: orders, Total: total, Page: page, PageSize: pageSize, Truncated: offset+len(orders) < total}, nil
}
// ErrorMessage 将分析失败阶段映射为原有 HTTP 错误消息。
func ErrorMessage(err error) string {
// stageErr 是带查询阶段的应用服务错误。
var stageErr *StageError
if !errors.As(err, &stageErr) {
return "查询失败"
}
switch stageErr.Stage {
case StageRevenue:
return "查询收益统计失败"
case StageDaily:
return "查询每日统计失败"
case StageStatus:
return "查询状态统计失败"
case StageCity:
return "查询城市统计失败"
case StageItem:
return "查询商品统计失败"
default:
return "查询失败"
}
}
// filter 将用户本地日期查询转换为数据库 UTC 范围并复制状态集合。
func (query Query) filter() Filter {
// statuses 是固定有效状态的独立副本,避免调用方修改全局集合。
statuses := append([]string(nil), ValidOrderStatuses...)
return Filter{UserID: query.UserID, StartAt: dateBoundary(query.StartDate, false, query.Location), EndBefore: dateBoundary(query.EndDate, true, query.Location), Statuses: statuses}
}
// dailyValue 保存单个日期的订单数和金额累计值。
type dailyValue struct {
// count 是当前日期的订单数量。
count int
// amount 是当前日期的金额累计值。
amount float64
}
// statusValue 保存单个归一化状态的订单数和金额累计值。
type statusValue struct {
// count 是当前状态的订单数量。
count int
// amount 是当前状态的金额累计值。
amount float64
}
// dateBoundary 是内部日期边界转换实现。
func dateBoundary(raw string, endExclusive bool, location *time.Location) string {
return DateBoundary(raw, endExclusive, location)
}
// parseDBTime 将数据库常见时间文本解析为 UTC 时间。
func parseDBTime(raw string) time.Time {
// layouts 是支持的数据库时间格式集合。
layouts := []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"}
// layout 是当前尝试的数据库时间格式。
for _, layout := range layouts {
// parsed 是当前格式尝试得到的时间值。
parsed, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC)
if err == nil {
return parsed
}
}
return time.Time{}
}
// parseAmount 将订单金额文本转换为数值。
func parseAmount(raw string) float64 {
// cleaned 是移除货币符号和千分位后的金额文本。
cleaned := strings.TrimSpace(strings.NewReplacer("¥", "", ",", "").Replace(raw))
// value 是解析后的金额;非法金额按零处理以保持历史统计口径。
value, _ := strconv.ParseFloat(cleaned, 64)
return value
}
// round2 将金额按两位小数进行四舍五入。
func round2(value float64) float64 {
return float64(int(value*100+0.5)) / 100
}
// normalizeStatus 将历史数字状态码归一为业务状态名称。
func normalizeStatus(status string) string {
// normalized 是历史平台数字状态到业务名称的兼容映射。
normalized, ok := map[string]string{
"paid": "pending_ship", "1": "processing", "2": "pending_ship", "3": "shipped", "4": "completed",
"5": "refunding", "6": "cancelled", "7": "refunding", "8": "cancelled", "9": "refunding", "10": "cancelled", "11": "completed", "12": "cancelled",
}[status]
if ok {
return normalized
}
if status == "" {
return "unknown"
}
return status
}
// itemImageFromDetail 从商品详情 JSON 中提取主图地址。
func itemImageFromDetail(detail string) string {
if detail == "" {
return ""
}
// payload 是商品详情的动态 JSON 对象。
var payload map[string]any
if // err 是商品详情 JSON 解析错误。
err := json.Unmarshal([]byte(detail), &payload); err != nil {
return ""
}
// picture 是商品详情中的图片信息对象。
if picture, ok := payload["pic_info"].(map[string]any); ok {
if // url、ok 是图片地址及其类型判断结果。
url, ok := picture["picUrl"].(string); ok {
return url
}
}
if // url、ok 是兼容图片地址及其类型判断结果。
url, ok := payload["item_image"].(string); ok {
return url
}
return ""
}
@@ -0,0 +1,335 @@
package analytics
import (
"context"
"errors"
"testing"
"time"
)
// analyticsRepositoryFake 是订单分析应用服务测试使用的可控 Port 实现。
type analyticsRepositoryFake struct {
// dashboard 保存仪表盘统计结果。
dashboard DashboardStats
// stock 保存可用卡密库存数量。
stock int64
// revenue 保存收益聚合结果。
revenue RevenueStats
// daily 保存日期聚合原始记录。
daily []DailyRecord
// statuses 保存状态聚合原始记录。
statuses []StatusRecord
// cities 保存城市聚合原始记录。
cities []CityRecord
// items 保存商品聚合原始记录。
items []ItemRecord
// validOrders 保存有效订单原始记录。
validOrders []ValidOrderRecord
// total 保存有效订单总数。
total int
// err 保存所有测试 Port 调用返回的错误。
err error
// dashboardErr 保存仪表盘计数查询错误。
dashboardErr error
// stockErr 保存卡密库存查询错误。
stockErr error
// revenueErr 保存收益查询错误。
revenueErr error
// dailyErr 保存按日查询错误。
dailyErr error
// statusErr 保存按状态查询错误。
statusErr error
// cityErr 保存按城市查询错误。
cityErr error
// itemErr 保存按商品查询错误。
itemErr error
// countErr 保存有效订单总数查询错误。
countErr error
// rowsErr 保存有效订单明细查询错误。
rowsErr error
// receivedFilter 保存最近一次收到的查询条件。
receivedFilter Filter
// receivedLimit 保存最近一次分页大小。
receivedLimit int
// receivedOffset 保存最近一次分页偏移。
receivedOffset int
}
// DashboardStats 返回预置的仪表盘统计。
func (f *analyticsRepositoryFake) DashboardStats(context.Context, int64) (DashboardStats, error) {
if f.dashboardErr != nil {
return DashboardStats{}, f.dashboardErr
}
return f.dashboard, f.err
}
// AvailableCardStock 返回预置的可用卡密库存。
func (f *analyticsRepositoryFake) AvailableCardStock(context.Context, int64) (int64, error) {
if f.stockErr != nil {
return 0, f.stockErr
}
return f.stock, f.err
}
// QueryRevenue 返回预置的收益统计并记录筛选条件。
func (f *analyticsRepositoryFake) QueryRevenue(_ context.Context, filter Filter) (RevenueStats, error) {
f.receivedFilter = filter
if f.revenueErr != nil {
return RevenueStats{}, f.revenueErr
}
return f.revenue, f.err
}
// QueryDaily 返回预置的日期记录。
func (f *analyticsRepositoryFake) QueryDaily(context.Context, Filter) ([]DailyRecord, error) {
if f.dailyErr != nil {
return nil, f.dailyErr
}
return f.daily, f.err
}
// QueryStatus 返回预置的状态记录。
func (f *analyticsRepositoryFake) QueryStatus(context.Context, Filter) ([]StatusRecord, error) {
if f.statusErr != nil {
return nil, f.statusErr
}
return f.statuses, f.err
}
// QueryCity 返回预置的城市记录。
func (f *analyticsRepositoryFake) QueryCity(context.Context, Filter) ([]CityRecord, error) {
if f.cityErr != nil {
return nil, f.cityErr
}
return f.cities, f.err
}
// QueryItem 返回预置的商品记录。
func (f *analyticsRepositoryFake) QueryItem(context.Context, Filter) ([]ItemRecord, error) {
if f.itemErr != nil {
return nil, f.itemErr
}
return f.items, f.err
}
// CountValidOrders 返回预置的有效订单总数。
func (f *analyticsRepositoryFake) CountValidOrders(context.Context, Filter) (int, error) {
if f.countErr != nil {
return 0, f.countErr
}
return f.total, f.err
}
// ListValidOrders 返回预置的有效订单记录并记录分页参数。
func (f *analyticsRepositoryFake) ListValidOrders(_ context.Context, _ Filter, limit, offset int) ([]ValidOrderRecord, error) {
f.receivedLimit = limit
f.receivedOffset = offset
if f.rowsErr != nil {
return nil, f.rowsErr
}
return f.validOrders, f.err
}
// TestDashboardStatsUsesNarrowStockPort 验证仪表盘只依赖非敏感库存数量 Port。
func TestDashboardStatsUsesNarrowStockPort(t *testing.T) {
// repository 是带有预置摘要和库存的测试 Port。
repository := &analyticsRepositoryFake{dashboard: DashboardStats{TotalCookies: 2, TotalOrders: 5}, stock: 7}
// service 是待验证的订单分析应用服务。
service := NewService(repository)
// result、err 是应用服务返回的仪表盘结果和错误。
result, err := service.DashboardStats(context.Background(), 9)
if err != nil {
t.Fatalf("仪表盘查询失败: %v", err)
}
if result.TotalCookies != 2 || result.TotalOrders != 5 || result.AvailableCardStock != 7 {
t.Fatalf("仪表盘结果异常: %+v", result)
}
}
// TestOrderAnalyticsAggregatesAndConvertsLocalDate 验证订单分析聚合和本地日期转换。
func TestOrderAnalyticsAggregatesAndConvertsLocalDate(t *testing.T) {
// repository 是带有各维度订单记录的测试 Port。
repository := &analyticsRepositoryFake{
revenue: RevenueStats{TotalOrders: 2, TotalAmount: 12.345, AvgAmount: 6.789, UniqueBuyers: 2, UniqueItems: 1},
daily: []DailyRecord{
{OrderID: "one", Amount: "¥10.50", CreatedAt: "2026-06-27 16:30:00"},
{OrderID: "two", Amount: "abc", CreatedAt: "2026-06-27 17:00:00"},
},
statuses: []StatusRecord{{Status: "3", Count: 1, Amount: 8.5}, {Status: "shipped", Count: 1, Amount: 2}},
cities: []CityRecord{{City: "杭州", Count: 2, Amount: 10.5}},
items: []ItemRecord{{ItemID: "item-1", Count: 2, TotalAmount: 10.5, AvgAmount: 5.25}},
}
// service 是待验证的订单分析应用服务。
service := NewService(repository)
// location 是 UTC+8 的用户本地时区。
location := time.FixedZone("UTC+8", 8*60*60)
// result、err 是应用服务返回的完整分析结果和错误。
result, err := service.OrderAnalytics(context.Background(), Query{UserID: 7, StartDate: "2026-06-28", EndDate: "2026-06-28", Location: location})
if err != nil {
t.Fatalf("订单分析失败: %v", err)
}
if len(result.DailyStats) != 1 || result.DailyStats[0].Date != "2026-06-28" || result.DailyStats[0].Amount != 10.5 {
t.Fatalf("日期统计异常: %+v", result.DailyStats)
}
if len(result.StatusStats) != 1 || result.StatusStats[0].Status != "shipped" || result.StatusStats[0].Count != 2 {
t.Fatalf("状态统计异常: %+v", result.StatusStats)
}
if result.RevenueStats.TotalAmount != 12.35 || result.RevenueStats.AvgAmount != 6.79 {
t.Fatalf("收益四舍五入异常: %+v", result.RevenueStats)
}
if repository.receivedFilter.UserID != 7 || repository.receivedFilter.StartAt != "2026-06-27 16:00:00" || repository.receivedFilter.EndBefore != "2026-06-28 16:00:00" {
t.Fatalf("筛选条件异常: %+v", repository.receivedFilter)
}
}
// TestValidOrdersMapsLegacyStatusAndPagination 验证有效订单分页保留兼容字段和主图。
func TestValidOrdersMapsLegacyStatusAndPagination(t *testing.T) {
// repository 是带有数字状态和商品详情的测试 Port。
repository := &analyticsRepositoryFake{total: 4, validOrders: []ValidOrderRecord{{
OrderID: "order-1", ItemID: "item-1", ItemTitle: "商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/1.png"}}`,
Status: "3", Amount: "9.90", Quantity: "1", CookieID: "cookie-1",
}}}
// service 是待验证的订单分析应用服务。
service := NewService(repository)
// result、err 是应用服务返回的分页结果和错误。
result, err := service.ValidOrders(context.Background(), Query{UserID: 1}, 2, 2)
if err != nil {
t.Fatalf("有效订单查询失败: %v", err)
}
if result.Page != 2 || result.PageSize != 2 || !result.Truncated || repository.receivedLimit != 2 || repository.receivedOffset != 2 {
t.Fatalf("分页结果异常: %+v limit=%d offset=%d", result, repository.receivedLimit, repository.receivedOffset)
}
if len(result.Orders) != 1 || result.Orders[0].Status != "shipped" || result.Orders[0].OrderStatus != "shipped" || result.Orders[0].ItemImage == "" {
t.Fatalf("有效订单映射异常: %+v", result.Orders)
}
}
// TestAnalyticsErrorsKeepQueryStage 验证查询失败仍保留阶段错误语义。
func TestAnalyticsErrorsKeepQueryStage(t *testing.T) {
// expected 是底层测试查询错误。
expected := errors.New("query failed")
// service 是返回底层错误的订单分析应用服务。
service := NewService(&analyticsRepositoryFake{err: expected})
// _, err 是收益阶段查询返回的错误。
_, err := service.OrderAnalytics(context.Background(), Query{})
if !errors.Is(err, expected) || ErrorMessage(err) != "查询收益统计失败" {
t.Fatalf("阶段错误异常: err=%v message=%s", err, ErrorMessage(err))
}
}
// TestAnalyticsErrorStagesCoverAllQueries 验证每个查询阶段错误都映射为稳定的兼容消息。
func TestAnalyticsErrorStagesCoverAllQueries(t *testing.T) {
// expected 是每个测试场景共用的底层查询错误。
expected := errors.New("stage query failed")
// cases 是查询阶段、构造测试 Port 和兼容错误消息的映射表。
cases := []struct {
// name 是测试场景名称。
name string
// repository 是注入对应阶段错误的测试 Port。
repository *analyticsRepositoryFake
// run 是触发当前阶段查询的应用用例调用。
run func(*Service) error
// message 是原有 HTTP 层需要保持的错误消息。
message string
}{
{name: "daily", repository: &analyticsRepositoryFake{dailyErr: expected}, run: func(service *Service) error {
// err 是每日查询阶段返回的错误。
_, err := service.OrderAnalytics(context.Background(), Query{})
return err
}, message: "查询每日统计失败"},
{name: "status", repository: &analyticsRepositoryFake{statusErr: expected}, run: func(service *Service) error {
// err 是状态查询阶段返回的错误。
_, err := service.OrderAnalytics(context.Background(), Query{})
return err
}, message: "查询状态统计失败"},
{name: "city", repository: &analyticsRepositoryFake{cityErr: expected}, run: func(service *Service) error {
// err 是城市查询阶段返回的错误。
_, err := service.OrderAnalytics(context.Background(), Query{})
return err
}, message: "查询城市统计失败"},
{name: "item", repository: &analyticsRepositoryFake{itemErr: expected}, run: func(service *Service) error {
// err 是商品查询阶段返回的错误。
_, err := service.OrderAnalytics(context.Background(), Query{})
return err
}, message: "查询商品统计失败"},
{name: "valid-count", repository: &analyticsRepositoryFake{countErr: expected}, run: func(service *Service) error {
// err 是有效订单总数查询阶段返回的错误。
_, err := service.ValidOrders(context.Background(), Query{}, 1, 10)
return err
}, message: "查询失败"},
{name: "valid-rows", repository: &analyticsRepositoryFake{rowsErr: expected}, run: func(service *Service) error {
// err 是有效订单明细查询阶段返回的错误。
_, err := service.ValidOrders(context.Background(), Query{}, 1, 10)
return err
}, message: "查询失败"},
}
// item 是当前遍历的阶段错误场景。
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
// err 是当前阶段用例返回的错误。
err := item.run(NewService(item.repository))
if !errors.Is(err, expected) || ErrorMessage(err) != item.message {
t.Fatalf("阶段错误异常: err=%v message=%s", err, ErrorMessage(err))
}
})
}
// dashboardCases 是仪表盘两个查询阶段的错误场景。
dashboardCases := []struct {
// name 是测试场景名称。
name string
// repository 是注入错误的测试 Port。
repository *analyticsRepositoryFake
}{
{name: "dashboard-count", repository: &analyticsRepositoryFake{dashboardErr: expected}},
{name: "dashboard-stock", repository: &analyticsRepositoryFake{stockErr: expected}},
}
// item 是当前遍历的仪表盘错误场景。
for _, item := range dashboardCases {
t.Run(item.name, func(t *testing.T) {
// err 是当前仪表盘用例返回的错误。
_, err := NewService(item.repository).DashboardStats(context.Background(), 1)
if !errors.Is(err, expected) {
t.Fatalf("仪表盘错误未保留: %v", err)
}
})
}
}
// TestAnalyticsCompatibilityHelpersCoverFallbacks 验证日期、状态和商品图片兼容回退。
func TestAnalyticsCompatibilityHelpersCoverFallbacks(t *testing.T) {
// location 是边界转换使用的测试时区。
location := time.FixedZone("UTC+8", 8*60*60)
if // got 是非法起始日期回退后的原始文本。
got := DateBoundary("invalid", false, location); got != "invalid" {
t.Fatalf("非法日期应保留原文本: %q", got)
}
if // got 是非法偏移回退后的本地时区。
got := LocationFromOffset("invalid"); got != time.Local {
t.Fatalf("非法时区偏移应回退本地时区: %v", got)
}
if // got 是空状态归一后的未知状态名称。
got := normalizeStatus(""); got != "unknown" || normalizeStatus("custom") != "custom" {
t.Fatalf("状态回退异常: empty=%q custom=%q", got, normalizeStatus("custom"))
}
// repository 是带有兼容图片字段的测试 Port。
repository := &analyticsRepositoryFake{total: 1, validOrders: []ValidOrderRecord{{OrderID: "fallback", ItemDetail: `{"item_image":"https://img.example/fallback.png"}`}}}
// result、err 是兼容图片字段映射结果和错误。
result, err := NewService(repository).ValidOrders(context.Background(), Query{}, 1, 1)
if err != nil || len(result.Orders) != 1 || result.Orders[0].ItemImage == "" {
t.Fatalf("兼容图片回退异常: result=%+v err=%v", result, err)
}
}
// TestDateBoundaryConvertsLocalDayToUTC 验证用户本地日期边界转换为 UTC 文本。
func TestDateBoundaryConvertsLocalDayToUTC(t *testing.T) {
// location 是 UTC+8 的测试时区。
location := time.FixedZone("UTC+8", 8*60*60)
if // got 是起始日期转换后的 UTC 边界。
got := DateBoundary("2026-06-28", false, location); got != "2026-06-27 16:00:00" {
t.Fatalf("起始边界=%q", got)
}
if // got 是结束日期转换后的 UTC 边界。
got := DateBoundary("2026-06-28", true, location); got != "2026-06-28 16:00:00" {
t.Fatalf("结束边界=%q", got)
}
}
@@ -0,0 +1,175 @@
// Package automation 提供自动化业务用例的纯应用层编排。
package automation
import (
"context"
"errors"
"regexp"
"strings"
)
// ErrUnavailable 表示账号任务运行所需的自动化中心尚未装配。
var ErrUnavailable = errors.New("自动化中心未启用")
// ErrInvalidTaskType 表示请求未使用受支持的账号任务类型。
var ErrInvalidTaskType = errors.New("不支持的任务类型")
// TaskAutoRate 表示自动评价任务。
const TaskAutoRate = "auto_rate"
// TaskAutoPolish 表示商品擦亮任务。
const TaskAutoPolish = "auto_polish"
// accountTaskTimePattern 校验擦亮任务每天执行的本地时间格式。
var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`)
// AccountTaskSettings 是不含数据库模型的账号任务设置。
type AccountTaskSettings struct {
// CookieID 是设置所属的账号标识。
CookieID string `json:"account_id"`
// AutoRateEnabled 表示是否启用自动评价。
AutoRateEnabled bool `json:"auto_rate_enabled"`
// RateContent 是自动评价使用的文字内容。
RateContent string `json:"rate_content"`
// AutoPolishEnabled 表示是否启用商品擦亮。
AutoPolishEnabled bool `json:"auto_polish_enabled"`
// PolishTime 是每天执行擦亮的本地时间,格式为 HH:mm。
PolishTime string `json:"polish_time"`
// LastRateScanAt 是上次扫描待评价订单的 Unix 秒时间。
LastRateScanAt int64 `json:"last_rate_scan_at"`
// LastPolishDate 是上次擦亮日期,使用 YYYY-MM-DD 格式。
LastPolishDate string `json:"last_polish_date"`
// LastPolishAt 是上次擦亮完成的 Unix 秒时间。
LastPolishAt int64 `json:"last_polish_at"`
}
// AccountTaskRun 是面向应用层的账号任务运行记录。
type AccountTaskRun struct {
// ID 是运行记录的持久化标识。
ID int64 `json:"id"`
// RunKey 是用于幂等去重的运行键。
RunKey string `json:"run_key"`
// CookieID 是运行所属的账号标识。
CookieID string `json:"account_id"`
// TaskType 是账号任务类型。
TaskType string `json:"task_type"`
// TargetID 是本次运行对应的平台对象标识。
TargetID string `json:"target_id"`
// RunDate 是任务业务日期。
RunDate string `json:"run_date"`
// Status 是运行当前状态。
Status string `json:"status"`
// SuccessCount 是外部动作成功数量。
SuccessCount int `json:"success_count"`
// FailedCount 是外部动作失败数量。
FailedCount int `json:"failed_count"`
// ErrorMessage 是供人工核对的非敏感错误摘要。
ErrorMessage string `json:"error_message"`
// NextRetryAt 是下一次重试的 Unix 秒时间。
NextRetryAt int64 `json:"next_retry_at"`
// StartedAt 是运行开始的 Unix 秒时间。
StartedAt int64 `json:"started_at"`
// FinishedAt 是运行结束的 Unix 秒时间。
FinishedAt int64 `json:"finished_at"`
}
// TaskSummary 是手动执行账号任务后的统计结果。
type TaskSummary struct {
// TaskType 是本次执行的任务类型。
TaskType string `json:"task_type"`
// Found 是发现的待处理对象数量。
Found int `json:"found"`
// Success 是外部动作成功数量。
Success int `json:"success"`
// Failed 是外部动作失败数量。
Failed int `json:"failed"`
// Skipped 是因状态或幂等检查而跳过的数量。
Skipped int `json:"skipped"`
// Message 是面向操作人员的非敏感执行说明。
Message string `json:"message,omitempty"`
}
// Repository 定义账号任务设置和历史记录所需的最小持久化能力。
type Repository interface {
// GetSettings 读取账号任务设置,未创建设置时返回默认值。
GetSettings(ctx context.Context, accountID string) (AccountTaskSettings, error)
// SaveSettings 保存账号任务设置。
SaveSettings(ctx context.Context, settings AccountTaskSettings) error
// ListRuns 返回账号最近的任务运行记录。
ListRuns(ctx context.Context, accountID string, limit int) ([]AccountTaskRun, error)
}
// Runner 定义手动触发账号任务所需的运行能力。
type Runner interface {
// RunAccountTask 执行指定账号的一个自动化任务。
RunAccountTask(ctx context.Context, accountID, taskType string) (TaskSummary, error)
}
// Service 编排账号任务的设置、历史和手动执行用例。
type Service struct {
// repository 提供账号任务持久化能力。
repository Repository
// runner 提供自动化中心的手动执行能力。
runner Runner
}
// NewService 构造账号任务应用服务。
func NewService(repository Repository, runner Runner) *Service {
return &Service{repository: repository, runner: runner}
}
// GetSettings 读取指定账号的账号任务设置。
func (s *Service) GetSettings(ctx context.Context, accountID string) (AccountTaskSettings, error) {
if s == nil || s.repository == nil {
return AccountTaskSettings{}, errors.New("账号任务存储未初始化")
}
return s.repository.GetSettings(ctx, strings.TrimSpace(accountID))
}
// UpdateSettings 校验并保存账号任务设置,再读取数据库中的最终值。
func (s *Service) UpdateSettings(ctx context.Context, settings AccountTaskSettings) (AccountTaskSettings, error) {
if s == nil || s.repository == nil {
return AccountTaskSettings{}, errors.New("账号任务存储未初始化")
}
settings.CookieID = strings.TrimSpace(settings.CookieID)
settings.RateContent = strings.TrimSpace(settings.RateContent)
if settings.CookieID == "" {
return AccountTaskSettings{}, errors.New("账号标识不能为空")
}
if settings.AutoRateEnabled && settings.RateContent == "" {
return AccountTaskSettings{}, errors.New("启用自动评价时评价内容不能为空")
}
if len([]rune(settings.RateContent)) > 500 {
return AccountTaskSettings{}, errors.New("评价内容不能超过 500 个字符")
}
if !accountTaskTimePattern.MatchString(settings.PolishTime) {
return AccountTaskSettings{}, errors.New("擦亮时间格式必须为 HH:mm")
}
// err 表示账号任务设置写入失败。
if err := s.repository.SaveSettings(ctx, settings); err != nil {
return AccountTaskSettings{}, err
}
return s.repository.GetSettings(ctx, settings.CookieID)
}
// ListRuns 查询指定账号最近的任务运行记录。
func (s *Service) ListRuns(ctx context.Context, accountID string, limit int) ([]AccountTaskRun, error) {
if s == nil || s.repository == nil {
return nil, errors.New("账号任务存储未初始化")
}
if limit <= 0 || limit > 100 {
limit = 20
}
return s.repository.ListRuns(ctx, strings.TrimSpace(accountID), limit)
}
// Run 手动执行指定账号的账号任务。
func (s *Service) Run(ctx context.Context, accountID, taskType string) (TaskSummary, error) {
if s == nil || s.runner == nil {
return TaskSummary{}, ErrUnavailable
}
if taskType != TaskAutoRate && taskType != TaskAutoPolish {
return TaskSummary{}, ErrInvalidTaskType
}
return s.runner.RunAccountTask(ctx, strings.TrimSpace(accountID), taskType)
}
@@ -0,0 +1,134 @@
package automation
import (
"context"
"errors"
"strings"
"testing"
)
// accountTaskRepositoryFake 保存账号任务应用服务测试所需的内存状态。
type accountTaskRepositoryFake struct {
// settings 是按账号保存的任务设置。
settings AccountTaskSettings
// runs 是待返回的历史运行记录。
runs []AccountTaskRun
// saveErr 是保存设置时模拟的错误。
saveErr error
}
// GetSettings 返回测试设置。
func (r *accountTaskRepositoryFake) GetSettings(context.Context, string) (AccountTaskSettings, error) {
return r.settings, nil
}
// SaveSettings 保存测试设置。
func (r *accountTaskRepositoryFake) SaveSettings(_ context.Context, settings AccountTaskSettings) error {
if r.saveErr != nil {
return r.saveErr
}
r.settings = settings
return nil
}
// ListRuns 返回测试运行记录并保留调用上限。
func (r *accountTaskRepositoryFake) ListRuns(_ context.Context, _ string, limit int) ([]AccountTaskRun, error) {
if len(r.runs) > limit {
return r.runs[:limit], nil
}
return r.runs, nil
}
// accountTaskRunnerFake 保存手动执行调用参数。
type accountTaskRunnerFake struct {
// summary 是模拟的任务结果。
summary TaskSummary
// accountID 是最近一次执行的账号标识。
accountID string
// taskType 是最近一次执行的任务类型。
taskType string
}
// RunAccountTask 记录并返回测试任务结果。
func (r *accountTaskRunnerFake) RunAccountTask(_ context.Context, accountID, taskType string) (TaskSummary, error) {
r.accountID = accountID
r.taskType = taskType
return r.summary, nil
}
// TestServiceUpdateSettings 验证设置规范化、校验和最终值读取。
func TestServiceUpdateSettings(t *testing.T) {
// repository 保存测试用例的设置状态。
repository := &accountTaskRepositoryFake{}
// service 是待验证的账号任务应用服务。
service := NewService(repository, nil)
// stored 保存校验通过后的最终设置。
stored, err := service.UpdateSettings(context.Background(), AccountTaskSettings{
CookieID: " account-1 ", AutoRateEnabled: true, RateContent: " 交易愉快 ", PolishTime: "03:00",
})
if err != nil {
t.Fatal(err)
}
if stored.CookieID != "account-1" || stored.RateContent != "交易愉快" {
t.Fatalf("设置未按应用规则规范化: %+v", stored)
}
// saveErr 表示测试仓储未预置保存失败。
if saveErr := repository.saveErr; saveErr != nil {
t.Fatal(err)
}
}
// TestServiceRejectsInvalidSettings 验证非法设置不会进入仓储。
func TestServiceRejectsInvalidSettings(t *testing.T) {
// cases 保存需要拒绝的输入及稳定错误片段。
cases := []struct {
// name 是测试分支名称。
name string
// settings 是待校验的设置。
settings AccountTaskSettings
// want 是错误信息中应包含的业务提示。
want string
}{
{name: "missing content", settings: AccountTaskSettings{CookieID: "a", AutoRateEnabled: true, PolishTime: "03:00"}, want: "评价内容不能为空"},
{name: "invalid time", settings: AccountTaskSettings{CookieID: "a", PolishTime: "3:00"}, want: "格式必须"},
}
// testCase 是当前待验证的非法账号任务设置分支。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// repository 保存当前分支的持久化假对象。
repository := &accountTaskRepositoryFake{}
// err 保存非法设置返回的校验错误。
_, err := NewService(repository, nil).UpdateSettings(context.Background(), testCase.settings)
if err == nil || !strings.Contains(err.Error(), testCase.want) {
t.Fatalf("错误=%v,期望包含=%q", err, testCase.want)
}
})
}
}
// TestServiceRunValidatesTypeAndPropagatesRunner 验证任务类型校验和执行摘要透传。
func TestServiceRunValidatesTypeAndPropagatesRunner(t *testing.T) {
// runner 保存手动任务执行替身。
runner := &accountTaskRunnerFake{summary: TaskSummary{TaskType: TaskAutoRate, Success: 2}}
// service 是绑定执行替身的应用服务。
service := NewService(nil, runner)
// summary 保存合法任务的结果。
summary, err := service.Run(context.Background(), "account-1", TaskAutoRate)
if err != nil || summary.Success != 2 {
t.Fatalf("执行结果错误: summary=%+v err=%v", summary, err)
}
if runner.accountID != "account-1" || runner.taskType != TaskAutoRate {
t.Fatalf("执行参数错误: account=%q task=%q", runner.accountID, runner.taskType)
}
// invalidErr 保存非法任务类型返回的应用层错误。
if invalidErr := serviceRunInvalid(service); !errors.Is(invalidErr, ErrInvalidTaskType) {
t.Fatalf("非法任务类型错误=%v", err)
}
}
// serviceRunInvalid 返回非法任务类型错误,保持主测试只关注应用服务契约。
func serviceRunInvalid(service *Service) error {
// err 表示应用服务拒绝未知任务类型的契约错误。
_, err := service.Run(context.Background(), "account-1", "unknown")
return err
}
@@ -0,0 +1,40 @@
// Package automation 提供自动化业务用例的纯应用层编排。
package automation
import (
"context"
"errors"
"strings"
)
// CredentialWakeRepository 定义凭证恢复后唤醒账号任务所需的最小端口。
type CredentialWakeRepository interface {
// WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的自动化任务。
WakeCredentialBlocked(context.Context, string) error
}
// CredentialWakeService 编排凭证恢复后的自动化任务唤醒,不依赖数据库或 HTTP 类型。
type CredentialWakeService struct {
// repository 提供自动化任务唤醒的持久化能力。
repository CredentialWakeRepository
}
// NewCredentialWakeService 构造凭证恢复唤醒应用服务并校验依赖。
func NewCredentialWakeService(repository CredentialWakeRepository) (*CredentialWakeService, error) {
if repository == nil {
return nil, errors.New("凭证恢复唤醒 repository 未初始化")
}
return &CredentialWakeService{repository: repository}, nil
}
// WakeCredentialBlocked 唤醒指定账号的凭证阻塞任务,并拒绝空账号标识。
func (s *CredentialWakeService) WakeCredentialBlocked(ctx context.Context, accountID string) error {
if s == nil || s.repository == nil {
return errors.New("凭证恢复唤醒服务未初始化")
}
accountID = strings.TrimSpace(accountID)
if accountID == "" {
return errors.New("账号标识不能为空")
}
return s.repository.WakeCredentialBlocked(ctx, accountID)
}
@@ -0,0 +1,59 @@
package automation
import (
"context"
"errors"
"testing"
)
// credentialWakeRepositoryFake 是凭证恢复唤醒应用服务测试用的可控端口替身。
type credentialWakeRepositoryFake struct {
// accountID 保存最近一次收到的账号标识。
accountID string
// wakeErr 保存模拟的持久化唤醒错误。
wakeErr error
}
// WakeCredentialBlocked 记录唤醒请求并返回预置错误。
func (f *credentialWakeRepositoryFake) WakeCredentialBlocked(_ context.Context, accountID string) error {
f.accountID = accountID
return f.wakeErr
}
// TestCredentialWakeServiceValidatesAndForwards 验证凭证恢复唤醒的输入、转发和错误传播。
func TestCredentialWakeServiceValidatesAndForwards(t *testing.T) {
// repository 是接收应用层唤醒请求的测试端口。
repository := &credentialWakeRepositoryFake{}
// service 是绑定测试端口的凭证恢复唤醒服务。
// err 保存应用服务构造错误。
service, err := NewCredentialWakeService(repository)
if err != nil {
t.Fatalf("构造唤醒服务失败: %v", err)
}
// err 表示归一化账号标识后的唤醒调用错误。
if err := service.WakeCredentialBlocked(context.Background(), " acc1 "); err != nil {
t.Fatalf("唤醒账号失败: %v", err)
}
if repository.accountID != "acc1" {
t.Fatalf("账号标识未归一化: %q", repository.accountID)
}
// err 表示空账号标识被应用层拒绝的错误结果。
if err := service.WakeCredentialBlocked(context.Background(), " "); err == nil {
t.Fatal("空账号标识不应调用唤醒端口")
}
// wakeErr 是底层任务状态写入故障。
wakeErr := errors.New("唤醒写入失败")
repository.wakeErr = wakeErr
// err 表示底层任务状态写入故障向应用层传播的结果。
if err := service.WakeCredentialBlocked(context.Background(), "acc1"); !errors.Is(err, wakeErr) {
t.Fatalf("唤醒错误未传播: %v", err)
}
}
// TestNewCredentialWakeServiceRequiresRepository 验证凭证恢复唤醒服务拒绝缺失端口。
func TestNewCredentialWakeServiceRequiresRepository(t *testing.T) {
// _, err 保存缺少持久化端口时的构造错误。
if _, err := NewCredentialWakeService(nil); err == nil {
t.Fatal("缺少唤醒 repository 时不应构造成功")
}
}
@@ -0,0 +1,28 @@
package automation
import "context"
// PublishRuleRepository 定义批量发布成功后幂等准备自动化规则所需的最小持久化能力。
type PublishRuleRepository interface {
// EnsurePublishRule 确保同一发布商品的自动化规则只创建一次。
EnsurePublishRule(ctx context.Context, input RuleInput) error
}
// PublishRuleService 编排发布成功后的自动化规则幂等准备,不依赖 HTTP 或数据库模型。
type PublishRuleService struct {
// repository 保存调用方注入的发布自动化规则持久化端口。
repository PublishRuleRepository
}
// NewPublishRuleService 构造批量发布自动化规则应用服务。
func NewPublishRuleService(repository PublishRuleRepository) *PublishRuleService {
return &PublishRuleService{repository: repository}
}
// Ensure 确保发布自动化规则存在,并保留适配器返回的底层错误语义。
func (s *PublishRuleService) Ensure(ctx context.Context, input RuleInput) error {
if s == nil || s.repository == nil {
return ErrInvalidInput
}
return s.repository.EnsurePublishRule(ctx, input)
}
@@ -0,0 +1,64 @@
package automation
import (
"context"
"errors"
"testing"
)
// publishRuleRepositoryFake 保存发布自动化规则应用服务测试所需的最小仓储替身。
type publishRuleRepositoryFake struct {
// input 保存最近一次幂等准备收到的规则输入。
input RuleInput
// calls 记录幂等准备被调用的次数。
calls int
// err 是仓储替身需要返回的预设错误。
err error
}
// EnsurePublishRule 记录发布规则输入并返回预设错误。
func (f *publishRuleRepositoryFake) EnsurePublishRule(_ context.Context, input RuleInput) error {
f.input = input
f.calls++
return f.err
}
// TestPublishRuleServiceForwardsInput 验证发布规则应用服务只编排端口调用并保留输入。
func TestPublishRuleServiceForwardsInput(t *testing.T) {
// repository 是记录应用服务调用的仓储替身。
repository := &publishRuleRepositoryFake{}
// service 是绑定测试仓储的发布规则应用服务。
service := NewPublishRuleService(repository)
// input 是代表批量发布结果的最小自动化规则输入。
input := RuleInput{UserID: 7, CookieID: "account-1", ItemID: "item-1", Name: "付款后自动发货", TriggerType: TriggerOrderPaid, Actions: []ActionInput{{ActionType: ActionConfirmShipment, Enabled: true, SortOrder: 1}}}
// err 保存应用服务调用结果。
err := service.Ensure(context.Background(), input)
if err != nil {
t.Fatal(err)
}
if repository.calls != 1 || repository.input.UserID != input.UserID || repository.input.Actions[0].ActionType != ActionConfirmShipment {
t.Fatalf("应用服务未完整转发规则输入: calls=%d input=%+v", repository.calls, repository.input)
}
}
// TestPublishRuleServicePropagatesRepositoryError 验证发布规则准备失败不会被应用层吞掉。
func TestPublishRuleServicePropagatesRepositoryError(t *testing.T) {
// expectedErr 是仓储端模拟的持久化故障。
expectedErr := errors.New("database unavailable")
// service 是绑定故障仓储的发布规则应用服务。
service := NewPublishRuleService(&publishRuleRepositoryFake{err: expectedErr})
// err 保存应用服务返回的持久化错误。
err := service.Ensure(context.Background(), RuleInput{UserID: 1})
if !errors.Is(err, expectedErr) {
t.Fatalf("应透传仓储错误,err=%v", err)
}
}
// TestPublishRuleServiceRejectsMissingRepository 验证缺少发布规则持久化端口时返回参数错误。
func TestPublishRuleServiceRejectsMissingRepository(t *testing.T) {
// err 保存缺少仓储时的应用服务错误。
err := NewPublishRuleService(nil).Ensure(context.Background(), RuleInput{UserID: 1})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("缺少仓储应返回参数错误,err=%v", err)
}
}
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff. Show more