阶段七:完成 React Feature 化与前置重构收口
This commit is contained in:
1 parent
375e84d663
commit
1a228dc35c
305 files changed
+14179
-5431
No files matched your search
@@ -0,0 +1,91 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// AccountCookieWriter 将手动登录产生的明文 Cookie 限制在账号基础设施适配器内。
|
||||
// 该类型同时实现新增和更新两个应用端口;Cookie 只在当前请求创建的实例中短暂存在。
|
||||
type AccountCookieWriter struct {
|
||||
// repository 提供凭证锁、归属校验、加密写入和旧 Token 清理能力。
|
||||
repository accountapp.CredentialRepository
|
||||
// platformCredentials 提供更新既有账号时所需的平台窄凭证视图。
|
||||
platformCredentials accountapp.PlatformCredentialViewPort
|
||||
// cookies 保存当前请求的明文 Cookie;禁止写入日志、HTTP 响应或长期状态。
|
||||
cookies string
|
||||
// logger 记录旧 Token 清理失败;日志中不得包含 Cookie 内容。
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewAccountCookieWriter 构造一次请求范围的 Cookie 写入适配器。
|
||||
// 调用方应在使用后丢弃返回实例,避免明文 Cookie 跨请求存活。
|
||||
func NewAccountCookieWriter(
|
||||
repository accountapp.CredentialRepository,
|
||||
platformCredentials accountapp.PlatformCredentialViewPort,
|
||||
cookies string,
|
||||
logger *slog.Logger,
|
||||
) *AccountCookieWriter {
|
||||
return &AccountCookieWriter{
|
||||
repository: repository, platformCredentials: platformCredentials, cookies: cookies, logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateOwnedCookie 在凭证锁内原子校验归属、写入 Cookie 并清理旧连接 Token。
|
||||
// 锁只覆盖数据库凭证变更,不跨越外部网络或运行时操作;清理失败不会回滚主写入。
|
||||
func (w *AccountCookieWriter) CreateOwnedCookie(ctx context.Context, accountID string, userID int64) error {
|
||||
if w == nil || w.repository == nil {
|
||||
return errors.New("账号登录凭证 repository 未初始化")
|
||||
}
|
||||
// unlock 保护同一账号的凭证写入与旧连接 Token 清理,外部网络和运行时操作在锁外执行。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// writeErr 保存凭证写入错误;归属校验失败时直接返回且不清理 Token。
|
||||
writeErr := w.repository.CreateCookieOwned(ctx, accountID, w.cookies, userID)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;清理失败不回滚已经成功写入的 Cookie。
|
||||
clearErr := w.repository.ClearTokens(ctx, accountID)
|
||||
if clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、版本检查、Cookie 写入和旧 Token 清理。
|
||||
// 资料刷新等慢速后续动作由应用服务在释放锁后触发。
|
||||
func (w *AccountCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error {
|
||||
if w == nil || w.repository == nil || w.platformCredentials == nil {
|
||||
return errors.New("账号登录凭证端口未初始化")
|
||||
}
|
||||
// unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时 I/O。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。
|
||||
detail, loadErr := w.platformCredentials.LoadPlatformDetail(ctx, accountID)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
if detail == nil || detail.UserID != userID {
|
||||
return accountapp.ErrForbidden
|
||||
}
|
||||
if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision {
|
||||
return accountapp.ErrCredentialConflict
|
||||
}
|
||||
// updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。
|
||||
if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。
|
||||
if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ accountapp.CookieWriter = (*AccountCookieWriter)(nil)
|
||||
var _ accountapp.CookieUpdater = (*AccountCookieWriter)(nil)
|
||||
@@ -0,0 +1,179 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// TestAccountCookieWriterRejectsMissingPorts 验证请求范围凭证 writer 缺少仓储时不会伪装成功。
|
||||
func TestAccountCookieWriterRejectsMissingPorts(t *testing.T) {
|
||||
// writer 模拟尚未完成基础设施装配但已经携带明文 Cookie 的请求实例。
|
||||
writer := NewAccountCookieWriter(nil, nil, "sid=short-lived", nil)
|
||||
// createErr 保存新增凭证写入的装配错误。
|
||||
createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1)
|
||||
if createErr == nil {
|
||||
t.Fatal("缺少凭证仓储时新增 Cookie 不应伪装成功")
|
||||
}
|
||||
// updateErr 保存既有凭证更新的装配错误。
|
||||
updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 0)
|
||||
if updateErr == nil {
|
||||
t.Fatal("缺少凭证端口时更新 Cookie 不应伪装成功")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountCookieWriterUpdatesOwnedCookie 验证更新成功、跨用户拒绝和版本冲突均发生在适配器内。
|
||||
func TestAccountCookieWriterUpdatesOwnedCookie(t *testing.T) {
|
||||
// store、cleanup 保存包含测试账号凭证的 SQLite 存储及清理函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// repository 是绑定测试数据库的账号凭证仓储。
|
||||
repository := NewAccountLoginRepository(store)
|
||||
// platformCredentials 是只暴露平台窄视图的读取服务。
|
||||
platformCredentials, serviceErr := accountapp.NewPlatformCredentialService(repository)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造平台凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// detail、detailErr 保存更新前的凭证版本与归属信息。
|
||||
detail, detailErr := repository.LoadPlatformDetail(context.Background(), "cid")
|
||||
if detailErr != nil {
|
||||
t.Fatalf("读取测试凭证失败: %v", detailErr)
|
||||
}
|
||||
// writer 是只在本次更新请求中持有明文 Cookie 的适配器。
|
||||
writer := NewAccountCookieWriter(repository, platformCredentials, "sid=updated", nil)
|
||||
// updateErr 保存归属正确且版本匹配时的更新结果。
|
||||
updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID, detail.LastRefreshAt)
|
||||
if updateErr != nil {
|
||||
t.Fatalf("更新账号 Cookie 失败: %v", updateErr)
|
||||
}
|
||||
// updated、updatedErr 保存数据库中更新后的平台凭证视图。
|
||||
updated, updatedErr := repository.LoadPlatformDetail(context.Background(), "cid")
|
||||
if updatedErr != nil || updated.Value != "sid=updated" {
|
||||
t.Fatalf("更新后的 Cookie 不符合预期: detail=%+v err=%v", updated, updatedErr)
|
||||
}
|
||||
// forbiddenErr 保存跨用户更新的稳定应用错误。
|
||||
forbiddenErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID+1, 0)
|
||||
if !errors.Is(forbiddenErr, accountapp.ErrForbidden) {
|
||||
t.Fatalf("跨用户更新应拒绝,got %v", forbiddenErr)
|
||||
}
|
||||
// conflictErr 保存客户端版本落后时的并发冲突错误。
|
||||
conflictErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID, detail.LastRefreshAt-1)
|
||||
if !errors.Is(conflictErr, accountapp.ErrCredentialConflict) {
|
||||
t.Fatalf("过期版本应返回冲突,got %v", conflictErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountCookieWriterHonorsContext 验证平台视图查询收到取消信号后不会继续写入 Cookie。
|
||||
func TestAccountCookieWriterHonorsContext(t *testing.T) {
|
||||
// store、cleanup 保存用于取消路径验证的 SQLite 存储及清理函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// repository 是绑定测试数据库的账号凭证仓储。
|
||||
repository := NewAccountLoginRepository(store)
|
||||
// platformCredentials 是更新流程使用的窄凭证视图服务。
|
||||
platformCredentials, serviceErr := accountapp.NewPlatformCredentialService(repository)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造平台凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// writer 是待接收取消上下文的凭证更新适配器。
|
||||
writer := NewAccountCookieWriter(repository, platformCredentials, "sid=cancelled", nil)
|
||||
// ctx、cancel 保存已取消的请求上下文及其取消函数。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
// updateErr 保存取消后的数据库查询结果。
|
||||
updateErr := writer.UpdateOwnedCookie(ctx, "cid", 1, 0)
|
||||
if updateErr == nil {
|
||||
t.Fatal("取消上下文不应继续完成凭证更新")
|
||||
}
|
||||
}
|
||||
|
||||
// cookieWriterRepositoryFake 是凭证 writer 测试使用的最小仓储替身,可注入清理失败和写入失败。
|
||||
type cookieWriterRepositoryFake struct {
|
||||
// detail 是平台窄视图查询返回的账号归属与版本。
|
||||
detail *accountapp.CredentialDetail
|
||||
// createErr 是新增 Cookie 持久化时注入的错误。
|
||||
createErr error
|
||||
// updateErr 是更新 Cookie 持久化时注入的错误。
|
||||
updateErr error
|
||||
// clearErr 是旧 Token 清理时注入的错误。
|
||||
clearErr error
|
||||
// clearCalls 记录旧 Token 清理调用次数,用于确认主写入后仍执行补偿清理。
|
||||
clearCalls int
|
||||
// receivedCookies 保存适配器传入的明文 Cookie,仅用于当前测试断言,不输出到失败日志。
|
||||
receivedCookies string
|
||||
}
|
||||
|
||||
// LockCredentials 返回测试用的无阻塞解锁函数。
|
||||
func (f *cookieWriterRepositoryFake) LockCredentials(string) func() {
|
||||
return func() {}
|
||||
}
|
||||
|
||||
// CreateCookieOwned 记录新增 Cookie 并返回注入的数据库结果。
|
||||
func (f *cookieWriterRepositoryFake) CreateCookieOwned(_ context.Context, _ string, cookies string, _ int64) error {
|
||||
f.receivedCookies = cookies
|
||||
return f.createErr
|
||||
}
|
||||
|
||||
// LoadPlatformDetail 返回测试用的平台窄凭证视图。
|
||||
func (f *cookieWriterRepositoryFake) LoadPlatformDetail(ctx context.Context, _ string) (*accountapp.CredentialDetail, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return f.detail, nil
|
||||
}
|
||||
|
||||
// UpdateFlatCookieOwned 记录更新 Cookie 并返回注入的数据库结果。
|
||||
func (f *cookieWriterRepositoryFake) UpdateFlatCookieOwned(_ context.Context, _ *accountapp.CredentialDetail, cookies string) error {
|
||||
f.receivedCookies = cookies
|
||||
return f.updateErr
|
||||
}
|
||||
|
||||
// UpdateRenewalCookie 满足凭证仓储接口的会话写回方法;本测试不使用该路径。
|
||||
func (f *cookieWriterRepositoryFake) UpdateRenewalCookie(context.Context, string, string, string, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearTokens 记录清理次数并返回注入的清理结果。
|
||||
func (f *cookieWriterRepositoryFake) ClearTokens(context.Context, string) error {
|
||||
f.clearCalls++
|
||||
return f.clearErr
|
||||
}
|
||||
|
||||
// GetStatus 满足凭证仓储接口的账号状态查询方法;本测试不使用该路径。
|
||||
func (f *cookieWriterRepositoryFake) GetStatus(context.Context, string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// UpdateProfile 满足凭证仓储接口的资料更新方法;本测试不使用该路径。
|
||||
func (f *cookieWriterRepositoryFake) UpdateProfile(context.Context, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestAccountCookieWriterKeepsPrimaryWriteWhenTokenCleanupFails 验证旧 Token 清理失败不回滚已成功的 Cookie 写入。
|
||||
func TestAccountCookieWriterKeepsPrimaryWriteWhenTokenCleanupFails(t *testing.T) {
|
||||
// cleanupErr 是模拟旧连接 Token 已不可清理的基础设施错误。
|
||||
cleanupErr := errors.New("token cleanup unavailable")
|
||||
// repository 是可注入清理失败的凭证仓储替身。
|
||||
repository := &cookieWriterRepositoryFake{
|
||||
detail: &accountapp.CredentialDetail{ID: "cid", UserID: 1, LastRefreshAt: 7},
|
||||
clearErr: cleanupErr,
|
||||
}
|
||||
// logger 将脱敏清理告警写入丢弃流,避免测试输出任何凭证内容。
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
// writer 是携带本次请求 Cookie 的适配器实例。
|
||||
writer := NewAccountCookieWriter(repository, repository, "sid=new", logger)
|
||||
// createErr 保存新增 Cookie 主写入结果。
|
||||
createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1)
|
||||
if createErr != nil || repository.receivedCookies != "sid=new" || repository.clearCalls != 1 {
|
||||
t.Fatalf("清理失败不应回滚新增写入: err=%v cookies=%q clears=%d", createErr, repository.receivedCookies, repository.clearCalls)
|
||||
}
|
||||
// updateErr 保存既有 Cookie 主写入结果。
|
||||
updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 7)
|
||||
if updateErr != nil || repository.receivedCookies != "sid=new" || repository.clearCalls != 2 {
|
||||
t.Fatalf("清理失败不应回滚更新写入: err=%v cookies=%q clears=%d", updateErr, repository.receivedCookies, repository.clearCalls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// AccountDependencies 封装账号登录、认证和扫码用例所需的窄适配器构造能力。
|
||||
// 它只在 adapter 内部持有 Store,避免 Server 通过通用设施容器隐式获取账号仓储。
|
||||
type AccountDependencies struct {
|
||||
// store 是账号适配器共享的数据库入口,不向 Server 或应用层暴露。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewAccountDependencies 构造账号专用依赖,并在缺少数据库入口时立即返回错误。
|
||||
func NewAccountDependencies(store *db.Store) (*AccountDependencies, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("账号依赖 Store 不能为空")
|
||||
}
|
||||
return &AccountDependencies{store: store}, nil
|
||||
}
|
||||
|
||||
// NewAccountLoginRepository 创建账号凭证和资料仓储。
|
||||
func (d *AccountDependencies) NewAccountLoginRepository() *AccountLoginRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAccountLoginRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAccountSettingsRepository 创建账号设置仓储。
|
||||
func (d *AccountDependencies) NewAccountSettingsRepository() *AccountSettingsRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAccountSettingsRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAccountSummaryRepository 创建不读取敏感凭证的账号摘要仓储。
|
||||
func (d *AccountDependencies) NewAccountSummaryRepository() *AccountSummaryRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAccountSummaryRepository(d.store)
|
||||
}
|
||||
|
||||
// NewQRLoginRepository 创建扫码登录成功写入所需的凭证端口。
|
||||
func (d *AccountDependencies) NewQRLoginRepository() accountapp.QRLoginRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewQRLoginRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAuthenticationRepository 创建用户认证仓储。
|
||||
func (d *AccountDependencies) NewAuthenticationRepository() *AuthenticationRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAuthenticationRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAccountLoginAuditRepository 创建账号登录审计仓储。
|
||||
func (d *AccountDependencies) NewAccountLoginAuditRepository() *AccountLoginAuditRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAccountLoginAuditRepository(d.store)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestNewAccountDependenciesRejectsNilStore 确保账号专用依赖不会在缺少数据库入口时构造成功。
|
||||
func TestNewAccountDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies、err 分别保存构造结果和缺少 Store 时的错误。
|
||||
dependencies, err := NewAccountDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回账号依赖")
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("缺少 Store 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewAccountDependenciesCreatesTypedFactory 确保有效 Store 可创建全部账号窄适配器。
|
||||
func TestNewAccountDependenciesCreatesTypedFactory(t *testing.T) {
|
||||
// store 仅用于验证构造类型,不执行数据库读写。
|
||||
store := db.NewStore(nil, db.DialectSQLite)
|
||||
// dependencies、err 分别保存账号工厂和构造错误。
|
||||
dependencies, err := NewAccountDependencies(store)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAccountDependencies: %v", err)
|
||||
}
|
||||
if dependencies == nil {
|
||||
t.Fatal("有效 Store 应返回账号依赖")
|
||||
}
|
||||
if dependencies.NewAccountLoginRepository() == nil || dependencies.NewAccountSettingsRepository() == nil || dependencies.NewAccountSummaryRepository() == nil {
|
||||
t.Fatal("账号工厂应返回账号仓储")
|
||||
}
|
||||
if dependencies.NewQRLoginRepository() == nil || dependencies.NewAuthenticationRepository() == nil || dependencies.NewAccountLoginAuditRepository() == nil {
|
||||
t.Fatal("账号工厂应返回认证与扫码端口")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// AccountLoginLifecycle 将登录审计、资料刷新、账号重启和扫码清理告警收口到适配器。
|
||||
// 它只组合应用层端口与日志能力,不持有 Server 或明文凭证。
|
||||
type AccountLoginLifecycle struct {
|
||||
// audit 负责记录登录方式、启用账号和写入审计日志。
|
||||
audit *accountapp.LoginAuditService
|
||||
// success 负责登录成功后的资料刷新与启用账号运行时重启。
|
||||
success *accountapp.LoginSuccessService
|
||||
// logger 记录不影响主流程的审计或清理告警,日志中不得包含 Cookie 内容。
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewAccountLoginLifecycle 构造手动登录和扫码登录共用的生命周期适配器。
|
||||
func NewAccountLoginLifecycle(audit *accountapp.LoginAuditService, success *accountapp.LoginSuccessService, logger *slog.Logger) *AccountLoginLifecycle {
|
||||
return &AccountLoginLifecycle{audit: audit, success: success, logger: logger}
|
||||
}
|
||||
|
||||
// AfterSuccessfulLogin 在凭证写入并释放凭证锁后记录审计并执行登录后续编排。
|
||||
func (l *AccountLoginLifecycle) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID, method string) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
// l.recordAudit 记录审计失败但不阻断已完成的凭证登录结果。
|
||||
l.recordAudit(ctx, userID, accountID, method, "账号登录成功")
|
||||
if l.success != nil {
|
||||
l.success.AfterSuccessfulLogin(ctx, userID, accountID)
|
||||
}
|
||||
}
|
||||
|
||||
// AfterSuccessfulQRLogin 在扫码凭证写入并释放凭证锁后记录扫码审计并执行后续编排。
|
||||
func (l *AccountLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
// l.recordAudit 记录扫码登录审计失败但不回滚已经写入的凭证。
|
||||
l.recordAudit(ctx, userID, accountID, accountapp.LoginMethodQRScan, "扫码登录成功")
|
||||
if l.success != nil {
|
||||
l.success.AfterSuccessfulLogin(ctx, userID, accountID)
|
||||
}
|
||||
}
|
||||
|
||||
// ReportQRLoginCleanupFailure 记录扫码成功后旧 Token 清理失败,不泄露 Cookie 内容。
|
||||
func (l *AccountLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) {
|
||||
if l != nil && l.logger != nil {
|
||||
l.logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// recordAudit 将登录审计错误降级为脱敏告警,保持凭证写入主流程的既有成功语义。
|
||||
func (l *AccountLoginLifecycle) recordAudit(ctx context.Context, userID int64, accountID, method, message string) {
|
||||
if l.audit == nil {
|
||||
return
|
||||
}
|
||||
// auditErr 保存审计应用服务返回的基础设施错误;错误日志不包含明文凭证。
|
||||
auditErr := l.audit.RecordSuccessfulLogin(ctx, accountapp.SuccessfulLoginInput{
|
||||
AccountID: accountID, UserID: userID, Method: method, Message: message,
|
||||
})
|
||||
if auditErr != nil && l.logger != nil {
|
||||
l.logger.Warn("记录账号登录审计失败", "cookie_id", accountID, "method", method, "err", auditErr)
|
||||
}
|
||||
}
|
||||
|
||||
var _ accountapp.LoginLifecyclePort = (*AccountLoginLifecycle)(nil)
|
||||
var _ accountapp.QRLoginLifecycle = (*AccountLoginLifecycle)(nil)
|
||||
@@ -0,0 +1,56 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// lifecycleAuditRepositoryFake 是生命周期适配器测试使用的登录审计仓储替身。
|
||||
type lifecycleAuditRepositoryFake struct {
|
||||
// methods 记录适配器提交的归一化登录方式。
|
||||
methods []string
|
||||
}
|
||||
|
||||
// MarkLogin 记录最近成功登录方式。
|
||||
func (f *lifecycleAuditRepositoryFake) MarkLogin(_ context.Context, _ string, method string, _ int64) error {
|
||||
f.methods = append(f.methods, method)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetStatusWithReason 满足审计仓储接口;生命周期测试不关心状态写入细节。
|
||||
func (f *lifecycleAuditRepositoryFake) SetStatusWithReason(context.Context, string, bool, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddLoginLog 满足审计仓储接口;登录方式已由 MarkLogin 记录。
|
||||
func (f *lifecycleAuditRepositoryFake) AddLoginLog(context.Context, accountapp.LoginAuditLog) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestAccountLoginLifecycleRoutesManualAndQRSuccess 验证手动登录与扫码登录共用审计和后续编排端口。
|
||||
func TestAccountLoginLifecycleRoutesManualAndQRSuccess(t *testing.T) {
|
||||
// repository 保存测试登录审计调用记录。
|
||||
repository := &lifecycleAuditRepositoryFake{}
|
||||
// audit 保存使用测试仓储的应用审计服务。
|
||||
audit := accountapp.NewLoginAuditService(repository)
|
||||
// lifecycle 是不持有 Server 的登录生命周期适配器。
|
||||
lifecycle := NewAccountLoginLifecycle(audit, nil, nil)
|
||||
// manualErr 保存手动登录生命周期调用结果;该方法本身不返回审计错误。
|
||||
lifecycle.AfterSuccessfulLogin(context.Background(), 1, "manual-account", accountapp.LoginMethodManual)
|
||||
// lifecycle.AfterSuccessfulQRLogin 记录扫码登录方式并保持同一审计端口。
|
||||
lifecycle.AfterSuccessfulQRLogin(context.Background(), 1, "qr-account")
|
||||
if len(repository.methods) != 2 || repository.methods[0] != accountapp.LoginMethodManual || repository.methods[1] != accountapp.LoginMethodQRScan {
|
||||
t.Fatalf("登录生命周期未正确路由审计方式: %+v", repository.methods)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountLoginLifecycleAllowsMissingOptionalPorts 验证缺少可选应用服务和日志端口时仍安全返回。
|
||||
func TestAccountLoginLifecycleAllowsMissingOptionalPorts(t *testing.T) {
|
||||
// lifecycle 是仅用于验证 nil 安全性的零依赖适配器。
|
||||
lifecycle := NewAccountLoginLifecycle(nil, nil, nil)
|
||||
lifecycle.AfterSuccessfulLogin(context.Background(), 1, "account", accountapp.LoginMethodManual)
|
||||
lifecycle.AfterSuccessfulQRLogin(context.Background(), 1, "account")
|
||||
lifecycle.ReportQRLoginCleanupFailure(context.Background(), "account", nil)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
accountmanager "xianyu-go/internal/account"
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
)
|
||||
|
||||
// AccountRuntimePort 将账号 Manager 的 engine 状态和生命周期能力映射为应用层运行时端口。
|
||||
type AccountRuntimePort struct {
|
||||
// manager 持有账号运行实例及其并发关闭语义;Server 不直接读取其 engine 状态。
|
||||
manager *accountmanager.Manager
|
||||
}
|
||||
|
||||
// NewAccountRuntimePort 创建账号运行时适配器;nil Manager 表示当前进程未启用账号运行实例。
|
||||
func NewAccountRuntimePort(manager *accountmanager.Manager) accountapp.RuntimePort {
|
||||
if manager == nil {
|
||||
return nil
|
||||
}
|
||||
return AccountRuntimePort{manager: manager}
|
||||
}
|
||||
|
||||
// AccountRunningLookup 创建订单等应用适配器使用的账号在线查询函数。
|
||||
// Manager 的具体运行实例和锁语义只在 adapter 内部读取,调用方只获得布尔结果。
|
||||
func AccountRunningLookup(manager *accountmanager.Manager) func(string) bool {
|
||||
return func(accountID string) bool {
|
||||
if manager == nil {
|
||||
return false
|
||||
}
|
||||
// _, running 保存账号运行实例是否存在。
|
||||
_, running := manager.GetInstance(accountID)
|
||||
return running
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateCookie 将凭证同步到已运行的账号实例;不存在实例时保持幂等成功。
|
||||
func (p AccountRuntimePort) UpdateCookie(ctx context.Context, accountID, value string) error {
|
||||
// contextErr 保存同步前检查到的取消错误。
|
||||
if contextErr := contextError(ctx); contextErr != nil {
|
||||
return contextErr
|
||||
}
|
||||
if p.manager == nil {
|
||||
return nil
|
||||
}
|
||||
// sender、ok 保存账号运行实例发送句柄及其存在性。
|
||||
sender, ok := p.manager.GetInstance(accountID)
|
||||
if !ok || sender == nil {
|
||||
return nil
|
||||
}
|
||||
sender.UpdateCookie(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RuntimeStatuses 返回应用层状态快照,避免上层依赖 engine.RuntimeStatus。
|
||||
func (p AccountRuntimePort) RuntimeStatuses(ctx context.Context) (map[string]accountapp.RuntimeStatus, error) {
|
||||
// contextErr 保存状态读取前检查到的取消错误。
|
||||
if contextErr := contextError(ctx); contextErr != nil {
|
||||
return nil, contextErr
|
||||
}
|
||||
// result 保存转换为应用 DTO 后的账号状态快照。
|
||||
result := make(map[string]accountapp.RuntimeStatus)
|
||||
if p.manager == nil {
|
||||
return result, nil
|
||||
}
|
||||
// accountID、status 表示当前遍历的账号标识及其 engine 状态快照。
|
||||
for accountID, status := range p.manager.RuntimeStatuses() {
|
||||
result[accountID] = accountapp.RuntimeStatus{
|
||||
State: status.State, Message: status.Message, Connected: status.Connected, Failures: status.Failures,
|
||||
UpdatedAt: status.UpdatedAt, TokenAcquiredAt: status.TokenAcquiredAt, TokenExpiresAt: status.TokenExpiresAt,
|
||||
TokenRefreshAt: status.TokenRefreshAt, TokenRemainingSeconds: status.TokenRemainingSeconds,
|
||||
TokenRefreshStatus: status.TokenRefreshStatus,
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Restart 重启账号运行实例;取消和数据库读取错误沿 Manager 原语向上返回。
|
||||
func (p AccountRuntimePort) Restart(ctx context.Context, accountID string) error {
|
||||
// contextErr 保存重启前检查到的取消错误。
|
||||
if contextErr := contextError(ctx); contextErr != nil {
|
||||
return contextErr
|
||||
}
|
||||
if p.manager == nil {
|
||||
return nil
|
||||
}
|
||||
return p.manager.Restart(ctx, accountID)
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 将平台会话失效恢复请求转发给账号 Manager。
|
||||
func (p AccountRuntimePort) RecoverExpiredCredential(ctx context.Context, accountID string) bool {
|
||||
if contextError(ctx) != nil || p.manager == nil {
|
||||
return false
|
||||
}
|
||||
return p.manager.RecoverExpiredCredential(ctx, accountID)
|
||||
}
|
||||
|
||||
// contextError 检查运行时适配器执行前的取消状态,避免取消请求仍触发实例副作用。
|
||||
func contextError(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package adapter
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestAccountRunningLookupRejectsMissingManager 验证账号在线查询适配器在缺少管理器时安全返回离线。
|
||||
func TestAccountRunningLookupRejectsMissingManager(t *testing.T) {
|
||||
// lookup 保存未装配管理器时的在线查询函数。
|
||||
lookup := AccountRunningLookup(nil)
|
||||
if lookup("account") {
|
||||
t.Fatal("missing manager must report account offline")
|
||||
}
|
||||
}
|
||||
+84
-50
@@ -14,6 +14,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
automationapp "xianyu-go/internal/application/automation"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/chat"
|
||||
@@ -70,17 +72,19 @@ type Adapter struct {
|
||||
logger *slog.Logger
|
||||
automation *automation.Center
|
||||
notifier notifyNotifier
|
||||
renewSvc xrenew.Service
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
orderMTop orderDetailClient
|
||||
chat *chat.Service
|
||||
// credentialWake 负责凭证写回后的自动化任务唤醒;Adapter 只依赖应用端口,不直接决定任务状态。
|
||||
credentialWake accountapp.CredentialWakePort
|
||||
renewSvc xrenew.Service
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
orderMTop orderDetailClient
|
||||
chat *chat.Service
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
|
||||
passwordMu sync.Mutex
|
||||
passwordProcessing map[string]struct{}
|
||||
// passwordCoordinator 按账号协调协议凭证恢复,避免重复外部续期并允许不同账号并行执行。
|
||||
passwordCoordinator *accountapp.CredentialRefreshCoordinator
|
||||
}
|
||||
|
||||
// notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包
|
||||
@@ -103,16 +107,32 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Adapter{
|
||||
store: store,
|
||||
browser: browserManagerOrNil(bm),
|
||||
logger: logger,
|
||||
cooldown: renewal.GlobalCooldown,
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordProcessing: make(map[string]struct{}),
|
||||
store: store,
|
||||
browser: browserManagerOrNil(bm),
|
||||
logger: logger,
|
||||
credentialWake: newCredentialWakeService(store),
|
||||
cooldown: renewal.GlobalCooldown,
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordCoordinator: accountapp.NewCredentialRefreshCoordinator(),
|
||||
}
|
||||
}
|
||||
|
||||
// newCredentialWakeService 构造凭证唤醒应用服务;数据库仓储仅在适配器边界内创建并隐藏。
|
||||
func newCredentialWakeService(store *db.Store) accountapp.CredentialWakePort {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
// repository 保存凭证唤醒所需的窄数据库适配器。
|
||||
repository := NewAutomationCredentialWakeRepository(store)
|
||||
// service、err 保存凭证唤醒应用服务及其装配错误。
|
||||
service, err := automationapp.NewCredentialWakeService(repository)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// browserManagerOrNil 把 *browser.Manager 转为接口;nil 时返回 nil 接口。
|
||||
func browserManagerOrNil(bm *browser.Manager) browserManager {
|
||||
if bm == nil {
|
||||
@@ -121,27 +141,30 @@ func browserManagerOrNil(bm *browser.Manager) browserManager {
|
||||
return bm
|
||||
}
|
||||
|
||||
// SetAutomation 注入自动化中心(系统事件转发目标)。
|
||||
// SetAutomation 注入系统事件的自动化中心;该 setter 仅保留给构造环过渡和隔离测试,待生产装配改为构造注入且旧测试清零后删除。
|
||||
func (a *Adapter) SetAutomation(c *automation.Center) { a.automation = c }
|
||||
|
||||
// SetNotifier 注入通知器(账号告警推送目标)。
|
||||
// SetNotifier 注入账号告警通知器;该 setter 仅保留给构造环过渡和隔离测试,待生产装配改为构造注入且旧测试清零后删除。
|
||||
func (a *Adapter) SetNotifier(n notifyNotifier) { a.notifier = n }
|
||||
|
||||
// SetBrowser 覆盖浏览器实现,便于测试注入桩。
|
||||
// SetCredentialWakeService 注入凭证恢复后的自动化唤醒端口;仅供构造环过渡和隔离测试,待统一应用装配后删除。
|
||||
func (a *Adapter) SetCredentialWakeService(service accountapp.CredentialWakePort) {
|
||||
a.credentialWake = service
|
||||
}
|
||||
|
||||
// SetBrowser 覆盖浏览器实现;生产启动后不得替换必需依赖,待测试改用构造选项后删除此兼容入口。
|
||||
func (a *Adapter) SetBrowser(b browserManager) { a.browser = b }
|
||||
|
||||
// SetRenewService 覆盖轻量续期服务,便于测试注入本地 HTTP 服务。
|
||||
// SetRenewService 覆盖轻量续期服务;该 setter 是测试替身覆盖点,待续期端口构造注入并迁移现有测试后删除。
|
||||
func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
|
||||
|
||||
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
|
||||
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器;仅供测试隔离网络,冻结验证码生产路径不得运行时替换。
|
||||
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
|
||||
|
||||
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
|
||||
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端;该 setter 是测试替身覆盖点,待订单端口构造注入并迁移测试后删除。
|
||||
func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
|
||||
// SetChatService installs the user-facing chat side channel. It persists and
|
||||
// broadcasts messages without changing the automatic reply path.
|
||||
// SetChatService 设置聊天Service。
|
||||
// SetChatService 注入用户聊天旁路服务;它只负责持久化和广播,不改变自动回复路径,待构造环拆除后删除兼容 setter。
|
||||
func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
@@ -541,11 +564,11 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
|
||||
// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.store == nil || a.store.Automation == nil {
|
||||
if a.credentialWake == nil {
|
||||
return
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
err := a.credentialWake.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -588,21 +611,39 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
if !a.beginPasswordLogin(cookieID) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
// platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。
|
||||
var platformData db.CookiePlatformRuntimeData
|
||||
// lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。
|
||||
lookupFailed := false
|
||||
// accepted、renewed、renewErr 保存协调器登记结果、续期结果和底层错误。
|
||||
accepted, renewed, renewErr := a.passwordCoordinator.Run(ctx, cookieID, func(runCtx context.Context) (bool, error) {
|
||||
// loaded、loadErr 保存账号平台运行数据及其读取错误。
|
||||
loaded, loadErr := a.store.Cookies.GetCookiePlatformRuntimeData(runCtx, cookieID)
|
||||
if loadErr != nil {
|
||||
lookupFailed = true
|
||||
return false, loadErr
|
||||
}
|
||||
platformData = loaded
|
||||
return a.tryProtocolCredentialRenew(runCtx, &platformData)
|
||||
})
|
||||
if !accepted {
|
||||
if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
a.logger.Warn("协议续期协调器不可用", "account", cookieID, "err", renewErr)
|
||||
return false
|
||||
}
|
||||
defer a.finishPasswordLogin(cookieID)
|
||||
|
||||
platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 是协议续期所需的 Cookie、metadata 和日志归属信息。
|
||||
if err != nil {
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error())
|
||||
if lookupFailed {
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", renewErr)
|
||||
// message 保存账号详情读取失败时写入登录审计的脱敏说明。
|
||||
message := "读取账号详情失败"
|
||||
if renewErr != nil {
|
||||
message = renewErr.Error()
|
||||
}
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", message)
|
||||
return false
|
||||
}
|
||||
|
||||
// renewed、renewErr 保存renewed、renewErr,供当前处理流程使用
|
||||
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, &platformData)
|
||||
if renewed {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "success", "", "Go 协议续期成功")
|
||||
@@ -634,26 +675,19 @@ func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// beginPasswordLogin 负责begin密码登录相关处理。
|
||||
// beginPasswordLogin 兼容旧测试对账号恢复登记的访问;生产路径统一使用 account.CredentialRefreshCoordinator.Run。
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
if a.passwordProcessing == nil {
|
||||
a.passwordProcessing = make(map[string]struct{})
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok := a.passwordProcessing[cookieID]; ok {
|
||||
if a.passwordCoordinator == nil {
|
||||
return false
|
||||
}
|
||||
a.passwordProcessing[cookieID] = struct{}{}
|
||||
return true
|
||||
return a.passwordCoordinator.TryBegin(cookieID)
|
||||
}
|
||||
|
||||
// finishPasswordLogin 负责finish密码登录相关处理。
|
||||
// finishPasswordLogin 兼容旧测试对账号恢复收尾的访问;正式调用必须由协调器 Run 自动释放状态。
|
||||
func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
delete(a.passwordProcessing, cookieID)
|
||||
if a.passwordCoordinator != nil {
|
||||
a.passwordCoordinator.Finish(cookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// recordPasswordLogin 负责record密码登录相关处理。
|
||||
|
||||
@@ -38,6 +38,14 @@ func (r *AdminRepository) ListUsers(ctx context.Context) ([]adminapp.UserSummary
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// ListOwnedAccountIDs 返回用户拥有的账号标识;适配器不会读取或解密 Cookie 内容。
|
||||
func (r *AdminRepository) ListOwnedAccountIDs(ctx context.Context, userID int64) ([]string, error) {
|
||||
if r == nil || r.store == nil || r.store.Cookies == nil {
|
||||
return nil, errors.New("管理员账号查询适配器未初始化")
|
||||
}
|
||||
return r.store.Cookies.ListOwnedIDs(ctx, userID)
|
||||
}
|
||||
|
||||
// DeleteUser 删除指定用户及其关联账号。
|
||||
func (r *AdminRepository) DeleteUser(ctx context.Context, userID int64) error {
|
||||
if r == nil || r.store == nil || r.store.Users == nil {
|
||||
|
||||
@@ -34,6 +34,11 @@ func TestAdminRepositoryMapsUsersStatsAndDelete(t *testing.T) {
|
||||
if targetErr != nil || target == nil {
|
||||
t.Fatalf("查询待删除用户失败 target=%v err=%v", target, targetErr)
|
||||
}
|
||||
// ownedIDs、ownedErr 保存管理员删除前读取的非敏感账号标识。
|
||||
ownedIDs, ownedErr := repository.ListOwnedAccountIDs(ctx, target.ID)
|
||||
if ownedErr != nil || ownedIDs == nil {
|
||||
t.Fatalf("读取用户账号标识异常 ids=%v err=%v", ownedIDs, ownedErr)
|
||||
}
|
||||
// deleteErr 保存管理员删除操作的错误。
|
||||
if deleteErr := repository.DeleteUser(ctx, target.ID); deleteErr != nil {
|
||||
t.Fatalf("删除用户失败: %v", deleteErr)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
adminapp "xianyu-go/internal/application/admin"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// AdminSettingsDependencies 封装管理员和系统设置应用服务所需的数据库适配器。
|
||||
type AdminSettingsDependencies struct {
|
||||
// store 保存管理员与设置适配器共享的数据库入口,仅在 adapter 内部使用。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewAdminSettingsDependencies 从数据库 Store 构造管理员设置专用依赖组。
|
||||
func NewAdminSettingsDependencies(store *db.Store) *AdminSettingsDependencies {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
return &AdminSettingsDependencies{store: store}
|
||||
}
|
||||
|
||||
// NewAdminRepository 创建管理员用户与统计适配器。
|
||||
func (d *AdminSettingsDependencies) NewAdminRepository() adminapp.Repository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAdminRepository(d.store)
|
||||
}
|
||||
|
||||
// NewSettingsRepository 创建系统设置适配器。
|
||||
func (d *AdminSettingsDependencies) NewSettingsRepository() *SettingsRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewSettingsRepository(d.store)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package adapter
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestNewAdminSettingsDependenciesRejectsNilStore 确保管理员设置依赖不会接受缺少数据库入口的构造请求。
|
||||
func TestNewAdminSettingsDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies 保存缺少 Store 时的管理员设置依赖结果。
|
||||
if dependencies := NewAdminSettingsDependencies(nil); dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回管理员设置依赖")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// AutomationDependencies 封装自动化、默认回复和关键词用例所需的窄适配器构造能力。
|
||||
// 它只在 adapter 内部持有 Store,避免 Server 通过通用设施容器隐藏领域依赖。
|
||||
type AutomationDependencies struct {
|
||||
// store 保存自动化相关适配器共享的数据库入口,不向 Server 或应用层暴露。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewAutomationDependencies 构造自动化领域专用依赖,并在缺少数据库入口时立即返回错误。
|
||||
func NewAutomationDependencies(store *db.Store) (*AutomationDependencies, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("自动化依赖 Store 不能为空")
|
||||
}
|
||||
return &AutomationDependencies{store: store}, nil
|
||||
}
|
||||
|
||||
// NewAutomationCredentialWakeRepository 创建凭证恢复后的自动化任务唤醒适配器。
|
||||
func (d *AutomationDependencies) NewAutomationCredentialWakeRepository() *AutomationCredentialWakeRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAutomationCredentialWakeRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAutomationRepository 创建自动化规则、异常和发布规则共用的数据库适配器。
|
||||
func (d *AutomationDependencies) NewAutomationRepository() *AutomationRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAutomationRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAccountTaskRepository 创建账号自动化任务设置与运行记录适配器。
|
||||
func (d *AutomationDependencies) NewAccountTaskRepository() *AccountTaskRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAccountTaskRepository(d.store)
|
||||
}
|
||||
|
||||
// NewDefaultReplyRepository 创建默认回复配置与投递记录适配器。
|
||||
func (d *AutomationDependencies) NewDefaultReplyRepository() *DefaultReplyRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewDefaultReplyRepository(d.store)
|
||||
}
|
||||
|
||||
// NewKeywordRepository 创建关键词和指定商品回复适配器。
|
||||
func (d *AutomationDependencies) NewKeywordRepository() *KeywordRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewKeywordRepository(d.store)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestNewAutomationDependenciesRejectsNilStore 确保自动化依赖组不会接受缺失数据库入口的半初始化状态。
|
||||
func TestNewAutomationDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies、err 分别保存构造结果和缺少 Store 时的错误。
|
||||
dependencies, err := NewAutomationDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回自动化依赖")
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("缺少 Store 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewAutomationDependenciesCreatesTypedFactory 确保有效 Store 可创建自动化与回复领域的全部窄适配器。
|
||||
func TestNewAutomationDependenciesCreatesTypedFactory(t *testing.T) {
|
||||
// store 仅用于验证构造类型,不执行数据库读写。
|
||||
store := db.NewStore(nil, db.DialectSQLite)
|
||||
// dependencies、err 分别保存自动化工厂和构造错误。
|
||||
dependencies, err := NewAutomationDependencies(store)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAutomationDependencies: %v", err)
|
||||
}
|
||||
if dependencies == nil {
|
||||
t.Fatal("有效 Store 应返回自动化依赖")
|
||||
}
|
||||
if dependencies.NewAutomationCredentialWakeRepository() == nil || dependencies.NewAutomationRepository() == nil || dependencies.NewAccountTaskRepository() == nil {
|
||||
t.Fatal("自动化工厂应返回自动化仓储")
|
||||
}
|
||||
if dependencies.NewDefaultReplyRepository() == nil || dependencies.NewKeywordRepository() == nil {
|
||||
t.Fatal("自动化工厂应返回回复规则仓储")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"xianyu-go/internal/account"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// ChatDependencies 封装聊天应用服务所需的数据库适配器工厂,避免 Server 依赖通用设施容器。
|
||||
type ChatDependencies struct {
|
||||
// store 保存聊天仓储共享的数据库入口,仅在 adapter 内部使用。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewChatDependencies 从数据库 Store 构造聊天专用依赖组。
|
||||
func NewChatDependencies(store *db.Store) *ChatDependencies {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
return &ChatDependencies{store: store}
|
||||
}
|
||||
|
||||
// NewChatSendingApplication 创建聊天应用服务及其平台、运行时和持久化适配器。
|
||||
func (d *ChatDependencies) NewChatSendingApplication(service *chat.Service, manager *account.Manager, client func() MTOPClient) *chatapp.Service {
|
||||
if d == nil {
|
||||
return NewChatSendingApplication(service, nil, manager, client)
|
||||
}
|
||||
return NewChatSendingApplication(service, d.store, manager, client)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/automation"
|
||||
domainchat "xianyu-go/internal/chat"
|
||||
)
|
||||
|
||||
// chatRefreshProvider 将账号运行时的平台分页能力与聊天领域落库服务收敛到应用端口。
|
||||
type chatRefreshProvider struct {
|
||||
// service 保存联系人和消息页的领域解析、幂等写入能力。
|
||||
service *domainchat.Service
|
||||
// lookup 按账号查找在线运行实例;运行时管理器只在适配器装配边界出现。
|
||||
lookup func(string) (automation.MessageSender, bool)
|
||||
}
|
||||
|
||||
// NewChatRefreshProvider 创建聊天平台刷新适配器。
|
||||
func NewChatRefreshProvider(service *domainchat.Service, manager *account.Manager) chatapp.RefreshProvider {
|
||||
if service == nil || manager == nil {
|
||||
return nil
|
||||
}
|
||||
return chatRefreshProvider{service: service, lookup: func(accountID string) (automation.MessageSender, bool) {
|
||||
return manager.GetInstance(accountID)
|
||||
}}
|
||||
}
|
||||
|
||||
// RefreshConversations 拉取联系人页并在领域服务中完成解析和持久化。
|
||||
func (p chatRefreshProvider) RefreshConversations(ctx context.Context, accountID string, cursor int64, limit int) (chatapp.ConversationPage, error) {
|
||||
if p.service == nil || p.lookup == nil {
|
||||
return chatapp.ConversationPage{}, chatapp.ErrRefreshUnavailable
|
||||
}
|
||||
// sender 和 ok 保存指定账号的在线运行实例及其存在性。
|
||||
sender, ok := p.lookup(accountID)
|
||||
if !ok || sender == nil {
|
||||
return chatapp.ConversationPage{}, chatapp.ErrOffline
|
||||
}
|
||||
// fetcher 和 supported 保存联系人平台分页能力及接口支持状态。
|
||||
fetcher, supported := sender.(interface {
|
||||
FetchChatConversations(context.Context, int64, int) (map[string]any, string, error)
|
||||
})
|
||||
if !supported {
|
||||
return chatapp.ConversationPage{}, errors.New("当前账号不支持聊天联系人刷新")
|
||||
}
|
||||
// body、myID 和 fetchErr 保存平台原始响应、当前账号身份及请求错误。
|
||||
body, myID, fetchErr := fetcher.FetchChatConversations(ctx, cursor, limit)
|
||||
if fetchErr != nil {
|
||||
return chatapp.ConversationPage{}, fetchErr
|
||||
}
|
||||
// page 和 saveErr 保存领域解析后的联系人分页结果及持久化错误。
|
||||
page, saveErr := p.service.RecordConversationPage(ctx, accountID, myID, body)
|
||||
if saveErr != nil {
|
||||
return chatapp.ConversationPage{}, fmt.Errorf("%w: %v", chatapp.ErrRefreshPersist, saveErr)
|
||||
}
|
||||
return chatapp.ConversationPage{HasMore: page.HasMore, NextCursor: page.NextCursor}, nil
|
||||
}
|
||||
|
||||
// RefreshHistory 拉取聊天历史页并在领域服务中完成解析和持久化。
|
||||
func (p chatRefreshProvider) RefreshHistory(ctx context.Context, accountID, chatID string, cursor int64, limit int, session chatapp.Session) (chatapp.HistoryPage, error) {
|
||||
if p.service == nil || p.lookup == nil {
|
||||
return chatapp.HistoryPage{}, chatapp.ErrRefreshUnavailable
|
||||
}
|
||||
// sender 和 ok 保存指定账号的在线运行实例及其存在性。
|
||||
sender, ok := p.lookup(accountID)
|
||||
if !ok || sender == nil {
|
||||
return chatapp.HistoryPage{}, chatapp.ErrOffline
|
||||
}
|
||||
// fetcher 和 supported 保存历史平台分页能力及接口支持状态。
|
||||
fetcher, supported := sender.(interface {
|
||||
FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error)
|
||||
})
|
||||
if !supported {
|
||||
return chatapp.HistoryPage{}, errors.New("当前账号不支持聊天历史刷新")
|
||||
}
|
||||
// body、myID 和 fetchErr 保存平台原始响应、当前账号身份及请求错误。
|
||||
body, myID, fetchErr := fetcher.FetchChatHistory(ctx, chatID, cursor, limit)
|
||||
if fetchErr != nil {
|
||||
return chatapp.HistoryPage{}, fetchErr
|
||||
}
|
||||
// page 和 saveErr 保存领域解析后的消息分页结果及持久化错误。
|
||||
page, saveErr := p.service.RecordHistoryPage(ctx, accountID, chatID, myID, ChatSessionFromApplication(session), body)
|
||||
if saveErr != nil {
|
||||
return chatapp.HistoryPage{}, fmt.Errorf("%w: %v", chatapp.ErrRefreshPersist, saveErr)
|
||||
}
|
||||
return chatapp.HistoryPage{
|
||||
Messages: ChatMessagesFromDB(page.Messages), Session: session,
|
||||
HasMore: page.HasMore, NextCursor: page.NextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 确保聊天刷新适配器覆盖应用层定义的全部能力。
|
||||
var _ chatapp.RefreshProvider = chatRefreshProvider{}
|
||||
@@ -6,10 +6,79 @@ import (
|
||||
"testing"
|
||||
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/automation"
|
||||
domainchat "xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// subscriptionDomainRepository 是领域聊天订阅测试使用的最小内存仓储。
|
||||
type subscriptionDomainRepository struct{}
|
||||
|
||||
// ListOwnedIDs 返回实时订阅测试账号归属。
|
||||
func (subscriptionDomainRepository) ListOwnedIDs(context.Context, int64) ([]string, error) {
|
||||
return []string{"cid"}, nil
|
||||
}
|
||||
|
||||
// DeleteSession 满足领域聊天仓储接口的删除能力。
|
||||
func (subscriptionDomainRepository) DeleteSession(context.Context, string, string) error { return nil }
|
||||
|
||||
// UpsertSession 满足领域聊天仓储接口的会话写入能力。
|
||||
func (subscriptionDomainRepository) UpsertSession(context.Context, db.ChatSession) error { return nil }
|
||||
|
||||
// SyncSessionSummary 满足领域聊天仓储接口的会话摘要同步能力。
|
||||
func (subscriptionDomainRepository) SyncSessionSummary(context.Context, string, string, string, int64, int64, int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveMessage 返回领域事件需要的消息副本,模拟幂等首次写入。
|
||||
func (subscriptionDomainRepository) SaveMessage(_ context.Context, _ db.ChatSession, message db.ChatMessage, _ bool) (*db.ChatMessage, bool, error) {
|
||||
return &message, true, nil
|
||||
}
|
||||
|
||||
// UpdateMessageType 满足领域聊天仓储接口的消息类型更新能力。
|
||||
func (subscriptionDomainRepository) UpdateMessageType(context.Context, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateMessageStatus 满足领域聊天仓储接口的消息状态更新能力。
|
||||
func (subscriptionDomainRepository) UpdateMessageStatus(context.Context, string, string, string) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{}, nil
|
||||
}
|
||||
|
||||
// TestChatSubscriptionProviderConvertsAndCleansEvents 验证领域事件转换和订阅取消可重复执行。
|
||||
func TestChatSubscriptionProviderConvertsAndCleansEvents(t *testing.T) {
|
||||
// service 是使用内存仓储构造的领域聊天事件中心。
|
||||
service := domainchat.NewWithRepository(subscriptionDomainRepository{})
|
||||
// provider 是隐藏领域模型并输出应用事件的适配器。
|
||||
provider := NewChatSubscriptionProvider(service)
|
||||
// events、cancel、err 保存适配器订阅结果。
|
||||
events, cancel, err := provider.Subscribe(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("Subscribe() error=%v", err)
|
||||
}
|
||||
// _, _, recordErr 保存领域入站消息写入结果。
|
||||
_, _, recordErr := service.RecordIncoming(context.Background(), domainchat.Incoming{
|
||||
AccountID: "cid", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", Text: "你好",
|
||||
Raw: map[string]any{"messageId": "msg-1"},
|
||||
})
|
||||
if recordErr != nil {
|
||||
t.Fatalf("RecordIncoming() error=%v", recordErr)
|
||||
}
|
||||
// event 保存转换后的应用层事件。
|
||||
event := <-events
|
||||
if event.Type != "message.created" || event.Message == nil || event.Message.MessageKey != "msg-1" || event.Message.Content != "你好" {
|
||||
t.Fatalf("event=%+v", event)
|
||||
}
|
||||
cancel()
|
||||
cancel()
|
||||
// closed 表示取消后转发通道已完成清理并关闭。
|
||||
_, closed := <-events
|
||||
if closed {
|
||||
t.Fatal("取消订阅后事件通道仍保持开启")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeChatUploadClient 只实现聊天图片上传能力,用于隔离平台网络请求。
|
||||
type fakeChatUploadClient struct {
|
||||
// mtop.Client 保留其余平台能力占位,测试只关注图片上传方法。
|
||||
@@ -33,6 +102,47 @@ type fakeChatIdentityClient struct {
|
||||
info *mtop.ChatUserInfo
|
||||
}
|
||||
|
||||
// fakeChatRefreshFetcher 提供联系人和历史分页的最小运行时能力,用于隔离账号管理器与平台连接。
|
||||
type fakeChatRefreshFetcher struct {
|
||||
// MessageSender 占位实现聊天发送端口未涉及的其余运行时方法。
|
||||
automation.MessageSender
|
||||
}
|
||||
|
||||
// FetchChatConversations 返回空联系人页,验证刷新适配器调用边界。
|
||||
func (fakeChatRefreshFetcher) FetchChatConversations(context.Context, int64, int) (map[string]any, string, error) {
|
||||
return map[string]any{"hasMore": true, "nextCursor": int64(8)}, "self", nil
|
||||
}
|
||||
|
||||
// FetchChatHistory 返回空历史页,验证刷新适配器调用边界。
|
||||
func (fakeChatRefreshFetcher) FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error) {
|
||||
return map[string]any{"hasMore": true, "nextCursor": int64(9)}, "self", nil
|
||||
}
|
||||
|
||||
// TestChatRefreshProviderKeepsPlatformAndDomainInsideAdapter 验证平台分页与领域落库均停留在适配器内。
|
||||
func TestChatRefreshProviderKeepsPlatformAndDomainInsideAdapter(t *testing.T) {
|
||||
// provider 保存使用内存领域仓储和测试运行时查找函数的刷新适配器。
|
||||
provider := chatRefreshProvider{
|
||||
service: domainchat.NewWithRepository(subscriptionDomainRepository{}),
|
||||
lookup: func(string) (automation.MessageSender, bool) { return fakeChatRefreshFetcher{}, true },
|
||||
}
|
||||
// conversations 和 conversationErr 保存联系人刷新结果及错误。
|
||||
conversations, conversationErr := provider.RefreshConversations(context.Background(), "cid", 0, 10)
|
||||
if conversationErr != nil || !conversations.HasMore || conversations.NextCursor != 8 {
|
||||
t.Fatalf("conversations=%+v err=%v", conversations, conversationErr)
|
||||
}
|
||||
// history 和 historyErr 保存历史刷新结果及错误。
|
||||
history, historyErr := provider.RefreshHistory(context.Background(), "cid", "chat", 0, 10, chatapp.Session{AccountID: "cid", ChatID: "chat"})
|
||||
if historyErr != nil || !history.HasMore || history.NextCursor != 9 {
|
||||
t.Fatalf("history=%+v err=%v", history, historyErr)
|
||||
}
|
||||
// unavailable 保存缺失运行实例查找函数时的应用端口错误。
|
||||
unavailable := chatRefreshProvider{service: provider.service}
|
||||
// unavailableErr 保存缺失运行时查找函数时的应用端口错误。
|
||||
if _, unavailableErr := unavailable.RefreshConversations(context.Background(), "cid", 0, 10); !errors.Is(unavailableErr, chatapp.ErrRefreshUnavailable) {
|
||||
t.Fatalf("unavailable error=%v", unavailableErr)
|
||||
}
|
||||
}
|
||||
|
||||
// FetchChatUserInfo 返回预设聊天身份,并记录适配器已能调用动态能力。
|
||||
func (c fakeChatIdentityClient) FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) {
|
||||
return c.info, nil
|
||||
|
||||
@@ -20,11 +20,17 @@ type chatOutgoingRepository struct {
|
||||
|
||||
// NewChatSendingApplication 装配聊天历史、实时发送、图片上传和身份补全端口。
|
||||
func NewChatSendingApplication(domainService *domainchat.Service, store *db.Store, manager *account.Manager, clientProvider func() mtop.Client) *chatapp.Service {
|
||||
return chatapp.NewWithSending(
|
||||
if domainService == nil {
|
||||
// service 保留历史查询应用对象,但不伪造未装配的发送、订阅和刷新端口。
|
||||
return chatapp.NewWithSendingSubscriptionAndRefresh(NewChatRepository(store), nil, nil, nil, nil, nil, NewChatIdentityResolver(store, clientProvider))
|
||||
}
|
||||
return chatapp.NewWithSendingSubscriptionAndRefresh(
|
||||
NewChatRepository(store),
|
||||
NewChatOutgoingRepository(domainService),
|
||||
NewChatSenderProvider(manager),
|
||||
NewChatImageUploader(store, clientProvider, manager),
|
||||
NewChatSubscriptionProvider(domainService),
|
||||
NewChatRefreshProvider(domainService, manager),
|
||||
NewChatIdentityResolver(store, clientProvider),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
domainchat "xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// chatSubscriptionProvider 将聊天领域事件转换为不暴露数据库模型的应用事件。
|
||||
type chatSubscriptionProvider struct {
|
||||
// service 保存聊天领域事件中心;HTTP 层只接收应用层事件。
|
||||
service *domainchat.Service
|
||||
}
|
||||
|
||||
// NewChatSubscriptionProvider 创建实时聊天订阅适配器。
|
||||
func NewChatSubscriptionProvider(service *domainchat.Service) chatapp.SubscriptionProvider {
|
||||
if service == nil {
|
||||
return nil
|
||||
}
|
||||
return chatSubscriptionProvider{service: service}
|
||||
}
|
||||
|
||||
// Subscribe 转发指定用户有权接收的领域事件,并由取消函数负责释放领域订阅和转发协程。
|
||||
func (p chatSubscriptionProvider) Subscribe(ctx context.Context, userID int64) (<-chan chatapp.Event, func(), error) {
|
||||
if p.service == nil || userID <= 0 {
|
||||
return nil, nil, chatapp.ErrSubscriptionUnavailable
|
||||
}
|
||||
// source 和 sourceCancel 保存领域订阅通道及其幂等清理函数。
|
||||
source, sourceCancel, err := p.service.Subscribe(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// forwardCtx 控制事件转换协程的退出;父请求结束时会自动取消。
|
||||
forwardCtx, cancelForward := context.WithCancel(ctx)
|
||||
// output 保存转换后的应用层事件,缓冲避免短暂写入抖动阻塞领域发布者。
|
||||
output := make(chan chatapp.Event, 128)
|
||||
// forwardDone 标记转发 goroutine 已退出,取消方等待它后再返回,避免留下游离后台任务。
|
||||
forwardDone := make(chan struct{})
|
||||
// stopOnce 保证调用方重复清理时不会重复关闭资源。
|
||||
var stopOnce sync.Once
|
||||
// stop 取消转发并释放领域订阅;调用方可在 WebSocket 握手失败和正常关闭路径重复调用。
|
||||
stop := func() {
|
||||
stopOnce.Do(func() {
|
||||
cancelForward()
|
||||
sourceCancel()
|
||||
})
|
||||
<-forwardDone
|
||||
}
|
||||
go func() {
|
||||
defer close(forwardDone)
|
||||
defer close(output)
|
||||
defer stopOnce.Do(func() {
|
||||
cancelForward()
|
||||
sourceCancel()
|
||||
})
|
||||
for {
|
||||
select {
|
||||
case <-forwardCtx.Done():
|
||||
return
|
||||
case // event、ok 保存领域事件及源订阅通道是否仍然开放。
|
||||
event, ok := <-source:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// converted 保存转换后的应用层事件,避免领域数据库模型越过适配器。
|
||||
converted := chatApplicationEvent(event)
|
||||
select {
|
||||
case output <- converted:
|
||||
case <-forwardCtx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return output, stop, nil
|
||||
}
|
||||
|
||||
// chatApplicationEvent 将领域事件中的数据库模型转换为敏感数据隔离后的应用模型。
|
||||
func chatApplicationEvent(event domainchat.Event) chatapp.Event {
|
||||
// converted 保存实时事件的非敏感应用层表示。
|
||||
converted := chatapp.Event{Type: event.Type}
|
||||
if event.Message != nil {
|
||||
// message 保存转换后的非敏感消息指针。
|
||||
message := chatApplicationMessage(event.Message)
|
||||
converted.Message = &message
|
||||
}
|
||||
if event.Session != nil {
|
||||
// session 保存转换后的非敏感会话摘要指针。
|
||||
session := chatApplicationSession(event.Session)
|
||||
converted.Session = &session
|
||||
}
|
||||
return converted
|
||||
}
|
||||
|
||||
// chatApplicationSession 将领域会话摘要转换为应用层会话摘要。
|
||||
func chatApplicationSession(session *db.ChatSession) chatapp.Session {
|
||||
if session == nil {
|
||||
return chatapp.Session{}
|
||||
}
|
||||
return chatapp.Session{
|
||||
AccountID: session.CookieID, ChatID: session.ChatID, BuyerID: session.BuyerID,
|
||||
BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID,
|
||||
ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt,
|
||||
UnreadCount: session.UnreadCount,
|
||||
}
|
||||
}
|
||||
|
||||
// 编译期确认实时聊天订阅适配器覆盖应用层端口。
|
||||
var _ chatapp.SubscriptionProvider = chatSubscriptionProvider{}
|
||||
@@ -47,7 +47,7 @@ func HasStoredCookieCredential(detail *accountapp.CredentialDetail) bool {
|
||||
// PersistCookieSessionLocked 持久化平台响应后的 Cookie 会话;调用方必须已持有凭证锁。
|
||||
func PersistCookieSessionLocked(
|
||||
ctx context.Context,
|
||||
repository accountapp.CredentialRepository,
|
||||
repository accountapp.CredentialSessionPort,
|
||||
detail *accountapp.CredentialDetail,
|
||||
session *CookieSession,
|
||||
) (value string, valueChanged, handled bool, err error) {
|
||||
|
||||
@@ -9,6 +9,18 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// minimalCredentialSessionPortFake 仅实现会话写回所需的方法,证明适配器不依赖完整账号仓储。
|
||||
type minimalCredentialSessionPortFake struct {
|
||||
// calls 记录平台会话写回次数。
|
||||
calls int
|
||||
}
|
||||
|
||||
// UpdateRenewalCookie 记录一次脱敏 Cookie 写回请求,不保存明文内容。
|
||||
func (f *minimalCredentialSessionPortFake) UpdateRenewalCookie(context.Context, string, string, string, int64) error {
|
||||
f.calls++
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestCookieSessionAdapterPersistsAuthoritativeSnapshot 验证平台 Cookie 会话快照经凭证 Port 写回并保留作用域。
|
||||
func TestCookieSessionAdapterPersistsAuthoritativeSnapshot(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库及其资源清理函数。
|
||||
@@ -57,6 +69,22 @@ func TestCookieSessionAdapterRejectsMissingRepository(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookieSessionAdapterAcceptsMinimalSessionPort 验证会话写回只要求最小凭证端口。
|
||||
func TestCookieSessionAdapterAcceptsMinimalSessionPort(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: "/"}})
|
||||
// port 保存仅实现 Cookie 写回能力的最小端口替身。
|
||||
port := &minimalCredentialSessionPortFake{}
|
||||
// _, changed、handled、persistErr 保存使用最小端口写回后的结果。
|
||||
_, changed, handled, persistErr := PersistCookieSessionLocked(ctx, port, detail, session)
|
||||
if persistErr != nil || !changed || !handled || port.calls != 1 {
|
||||
t.Fatalf("最小凭证端口写回异常: changed=%v handled=%v calls=%d err=%v", changed, handled, port.calls, persistErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookieSessionAdapterHasStoredCredential 验证扁平 Cookie 和完整快照均被识别为可用凭证。
|
||||
func TestCookieSessionAdapterHasStoredCredential(t *testing.T) {
|
||||
// flat 是只含扁平 Cookie 的历史平台凭证视图。
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// ItemDependencies 封装商品目录、发布、批量和同步用例所需的窄适配器构造能力。
|
||||
// 它只在 adapter 内部持有 Store,避免商品装配依赖通用设施容器。
|
||||
type ItemDependencies struct {
|
||||
// store 是商品适配器共享的数据库入口,不向 Server 或应用层暴露。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewItemDependencies 构造商品专用依赖,并在缺少数据库入口时立即返回错误。
|
||||
func NewItemDependencies(store *db.Store) (*ItemDependencies, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("商品依赖 Store 不能为空")
|
||||
}
|
||||
return &ItemDependencies{store: store}, nil
|
||||
}
|
||||
|
||||
// NewItemBatchRepository 创建批量发布状态仓储。
|
||||
func (d *ItemDependencies) NewItemBatchRepository() *ItemBatchRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemBatchRepository(d.store)
|
||||
}
|
||||
|
||||
// NewItemBatchPreviewPort 创建批量预检所需的归属和本地文件端口。
|
||||
func (d *ItemDependencies) NewItemBatchPreviewPort() *ItemBatchPreviewPort {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemBatchPreviewPort(d.store)
|
||||
}
|
||||
|
||||
// NewItemBatchPublishPort 创建批量远端发布端口,并接收平台会话与图片 I/O 回调。
|
||||
func (d *ItemDependencies) NewItemBatchPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error), readFile ReadPublishImageFile, download DownloadPublishImageURL) *ItemBatchPublishPort {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemBatchPublishPort(d.store, client, logger, update, recover, readFile, download)
|
||||
}
|
||||
|
||||
// NewItemPublishPort 创建单商品发布与类目推荐共用的平台端口。
|
||||
func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemPublishPort(d.store, client, logger, update, recover)
|
||||
}
|
||||
|
||||
// NewItemPublishRepository 创建单商品发布结果仓储。
|
||||
func (d *ItemDependencies) NewItemPublishRepository() *ItemPublishRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemPublishRepository(d.store)
|
||||
}
|
||||
|
||||
// NewItemCatalogRepository 创建商品目录读写仓储。
|
||||
func (d *ItemDependencies) NewItemCatalogRepository() *ItemCatalogRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemCatalogRepository(d.store)
|
||||
}
|
||||
|
||||
// NewItemSyncRepository 创建商品同步端口,并接收平台会话回调。
|
||||
func (d *ItemDependencies) NewItemSyncRepository(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemSyncRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewItemSyncRepository(d.store, client, logger, update, recover)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestNewItemDependenciesRejectsNilStore 确保商品专用依赖不会在缺少数据库入口时构造成功。
|
||||
func TestNewItemDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies、err 分别保存构造结果和缺少 Store 时的错误。
|
||||
dependencies, err := NewItemDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回商品依赖")
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("缺少 Store 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewItemDependenciesCreatesTypedFactory 确保有效 Store 可创建商品领域全部窄适配器。
|
||||
func TestNewItemDependenciesCreatesTypedFactory(t *testing.T) {
|
||||
// store 仅用于验证构造类型,不执行数据库读写。
|
||||
store := db.NewStore(nil, db.DialectSQLite)
|
||||
// dependencies、err 分别保存商品工厂和构造错误。
|
||||
dependencies, err := NewItemDependencies(store)
|
||||
if err != nil {
|
||||
t.Fatalf("NewItemDependencies: %v", err)
|
||||
}
|
||||
if dependencies == nil {
|
||||
t.Fatal("有效 Store 应返回商品依赖")
|
||||
}
|
||||
if dependencies.NewItemBatchRepository() == nil || dependencies.NewItemBatchPreviewPort() == nil || dependencies.NewItemPublishRepository() == nil || dependencies.NewItemCatalogRepository() == nil {
|
||||
t.Fatal("商品工厂应返回本地仓储和预检端口")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// MiscDependencies 封装通知、订单分析和卡券应用服务所需的数据库适配器构造能力。
|
||||
// 该依赖组只在适配器内部持有 Store,Server 通过领域方法获得窄接口,避免继续扩大通用设施容器的职责。
|
||||
type MiscDependencies struct {
|
||||
// store 保存通知、分析和卡券适配器共享的数据库入口,不向 HTTP 层或应用服务暴露。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewMiscDependencies 构造通知、分析和卡券领域专用依赖,并拒绝缺少数据库入口的半初始化实例。
|
||||
func NewMiscDependencies(store *db.Store) (*MiscDependencies, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("通知、分析和卡券依赖 Store 不能为空")
|
||||
}
|
||||
return &MiscDependencies{store: store}, nil
|
||||
}
|
||||
|
||||
// NewNotificationUncertainRepository 创建通知不确定状态查询适配器。
|
||||
func (d *MiscDependencies) NewNotificationUncertainRepository() notificationsapp.Repository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewNotificationUncertainRepository(d.store)
|
||||
}
|
||||
|
||||
// NewNotificationChannelRepository 创建通知渠道及账号绑定适配器。
|
||||
func (d *MiscDependencies) NewNotificationChannelRepository() notificationsapp.ChannelRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewNotificationChannelRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAnalyticsRepository 创建订单分析只读适配器。
|
||||
func (d *MiscDependencies) NewAnalyticsRepository() *AnalyticsRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAnalyticsRepository(d.store)
|
||||
}
|
||||
|
||||
// NewCardsRepository 创建卡券库存适配器。
|
||||
func (d *MiscDependencies) NewCardsRepository() *CardsRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewCardsRepository(d.store)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestNewMiscDependenciesRejectsNilStore 确保通知、分析和卡券依赖不会以缺失数据库入口的状态构造。
|
||||
func TestNewMiscDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies、err 分别保存构造结果和缺少 Store 时的错误。
|
||||
dependencies, err := NewMiscDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回杂项依赖")
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("缺少 Store 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewMiscDependenciesCreatesTypedFactories 确保有效 Store 能创建三个领域的窄适配器。
|
||||
func TestNewMiscDependenciesCreatesTypedFactories(t *testing.T) {
|
||||
// store 仅用于验证工厂构造,不执行数据库读写。
|
||||
store := db.NewStore(nil, db.DialectSQLite)
|
||||
// dependencies、err 分别保存杂项领域工厂和构造错误。
|
||||
dependencies, err := NewMiscDependencies(store)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMiscDependencies: %v", err)
|
||||
}
|
||||
if dependencies == nil {
|
||||
t.Fatal("有效 Store 应返回杂项领域依赖")
|
||||
}
|
||||
if dependencies.NewNotificationUncertainRepository() == nil || dependencies.NewNotificationChannelRepository() == nil {
|
||||
t.Fatal("通知工厂应返回两个通知应用仓储")
|
||||
}
|
||||
if dependencies.NewAnalyticsRepository() == nil {
|
||||
t.Fatal("分析工厂应返回分析仓储")
|
||||
}
|
||||
if dependencies.NewCardsRepository() == nil {
|
||||
t.Fatal("卡券工厂应返回卡券仓储")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMiscDependenciesNilReceiverReturnsNil 确保测试或关闭流程中的空依赖不会伪造适配器。
|
||||
func TestMiscDependenciesNilReceiverReturnsNil(t *testing.T) {
|
||||
// dependencies 表示未装配的杂项依赖接收者。
|
||||
var dependencies *MiscDependencies
|
||||
if dependencies.NewNotificationUncertainRepository() != nil || dependencies.NewNotificationChannelRepository() != nil || dependencies.NewAnalyticsRepository() != nil || dependencies.NewCardsRepository() != nil {
|
||||
t.Fatal("空杂项依赖不应创建任何适配器")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// OrderDependencies 只封装订单用例所需的持久化与运行时适配器构造,避免订单装配依赖万能设施容器。
|
||||
type OrderDependencies struct {
|
||||
// store 是订单适配器共享的数据库入口,仅在 adapter 内部用于创建窄接口实现。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewOrderDependencies 构造订单专用依赖并拒绝缺失数据库入口。
|
||||
func NewOrderDependencies(store *db.Store) (*OrderDependencies, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("订单依赖 Store 不能为空")
|
||||
}
|
||||
return &OrderDependencies{store: store}, nil
|
||||
}
|
||||
|
||||
// NewOrderRepository 创建订单读写仓储,供订单应用服务共享同一适配器实例。
|
||||
func (d *OrderDependencies) NewOrderRepository() *OrderRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewOrderRepository(d.store)
|
||||
}
|
||||
|
||||
// NewOrderReconciliationRepository 创建订单补偿记录仓储,供跨外部动作的异常收口使用。
|
||||
func (d *OrderDependencies) NewOrderReconciliationRepository() *OrderReconciliationRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewOrderReconciliationRepository(d.store)
|
||||
}
|
||||
|
||||
// NewOrderRuntime 创建订单平台运行时,调用方通过 hooks 注入账号、自动化和通知能力。
|
||||
func (d *OrderDependencies) NewOrderRuntime(hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewOrderRuntime(d.store, hooks, reconciliation, logger)
|
||||
}
|
||||
|
||||
// NewOrderRefreshJobRepository 创建订单刷新任务仓储,隐藏任务租约与状态的持久化模型。
|
||||
func (d *OrderDependencies) NewOrderRefreshJobRepository() orderapp.RefreshJobRepository {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewOrderRefreshJobRepository(d.store)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestNewOrderDependenciesRejectsNilStore 确保订单专用依赖不会在缺少数据库入口时构造成功。
|
||||
func TestNewOrderDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies、err 分别保存构造结果和缺少 Store 时的错误。
|
||||
dependencies, err := NewOrderDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回订单依赖")
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("缺少 Store 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewOrderDependenciesCreatesTypedFactory 确保有效 Store 能创建订单专用工厂并生成窄仓储。
|
||||
func TestNewOrderDependenciesCreatesTypedFactory(t *testing.T) {
|
||||
// store 使用已初始化的仓储聚合仅验证装配类型,不执行数据库读写。
|
||||
store := db.NewStore(nil, db.DialectSQLite)
|
||||
// dependencies、err 分别保存订单工厂和构造错误。
|
||||
dependencies, err := NewOrderDependencies(store)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrderDependencies: %v", err)
|
||||
}
|
||||
if dependencies == nil {
|
||||
t.Fatal("有效 Store 应返回订单依赖")
|
||||
}
|
||||
if dependencies.NewOrderRepository() == nil {
|
||||
t.Fatal("订单工厂应返回订单仓储")
|
||||
}
|
||||
if dependencies.NewOrderReconciliationRepository() == nil {
|
||||
t.Fatal("订单工厂应返回补偿仓储")
|
||||
}
|
||||
if dependencies.NewOrderRefreshJobRepository() == nil {
|
||||
t.Fatal("订单工厂应返回刷新任务仓储")
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,25 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
accountmanager "xianyu-go/internal/account"
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// OrderAutomation 定义订单手动发货所需的最小自动化能力,避免订单适配器依赖具体 Center 类型。
|
||||
type OrderAutomation interface {
|
||||
// ManualFullDelivery 执行一次订单完整发货并返回实际发送数量。
|
||||
ManualFullDelivery(context.Context, *db.Order) (int, error)
|
||||
}
|
||||
|
||||
// OrderNotifier 定义订单发货结果所需的最小通知能力,通知实现不进入订单应用层。
|
||||
type OrderNotifier interface {
|
||||
// NotifyDelivery 发送订单发货结果通知。
|
||||
NotifyDelivery(string, string, string, string, string, string)
|
||||
}
|
||||
|
||||
// orderDetailMTop 是订单运行时需要的可选详情接口能力。
|
||||
type orderDetailMTop interface {
|
||||
// FetchOrderDetail 请求订单详情并返回平台响应中的订单字段。
|
||||
@@ -42,6 +55,29 @@ type OrderRuntimeHooks struct {
|
||||
ReportPersistenceFailure func(string, error)
|
||||
}
|
||||
|
||||
// NewOrderRuntimeHooks 将账号、自动化和通知依赖转换为订单运行时回调;闭包只存在于 adapter 装配边界。
|
||||
func NewOrderRuntimeHooks(client func() mtop.Client, manager *accountmanager.Manager, automation OrderAutomation, notifier OrderNotifier, updateCookie func(context.Context, string, string), recoverSession func(context.Context, string, error) bool) OrderRuntimeHooks {
|
||||
return OrderRuntimeHooks{
|
||||
Client: client,
|
||||
ClientAvailable: func() bool { return client != nil && client() != nil },
|
||||
AccountRunning: AccountRunningLookup(manager),
|
||||
AutomationReady: func() bool { return manager != nil && automation != nil },
|
||||
ManualFullDelivery: func(ctx context.Context, order *orderapp.Order) (int, error) {
|
||||
if automation == nil {
|
||||
return 0, errors.New("自动化中心未初始化")
|
||||
}
|
||||
return automation.ManualFullDelivery(ctx, OrderForAutomation(order))
|
||||
},
|
||||
UpdateRunningCookie: updateCookie,
|
||||
NotifyDelivery: func(cookieID, buyerID, itemID, chatID, message string) {
|
||||
if notifier != nil {
|
||||
notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID)
|
||||
}
|
||||
},
|
||||
RecoverExpiredSession: recoverSession,
|
||||
}
|
||||
}
|
||||
|
||||
// OrderRuntime 将订单应用 Port 适配到数据库凭证、MTOP 和账号运行时。
|
||||
type OrderRuntime struct {
|
||||
// store 提供订单确认发货所需的平台凭证读取和 Cookie 写回能力。
|
||||
|
||||
@@ -6,9 +6,33 @@ import (
|
||||
"testing"
|
||||
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// orderRuntimeAutomationFake 是订单运行时测试使用的自动化能力替身。
|
||||
type orderRuntimeAutomationFake struct {
|
||||
// calls 记录自动化完整发货调用次数。
|
||||
calls int
|
||||
}
|
||||
|
||||
// ManualFullDelivery 返回固定发送数量,验证 adapter 的订单模型转换回调。
|
||||
func (f *orderRuntimeAutomationFake) ManualFullDelivery(context.Context, *db.Order) (int, error) {
|
||||
f.calls++
|
||||
return 2, nil
|
||||
}
|
||||
|
||||
// orderRuntimeNotifierFake 是订单运行时测试使用的通知能力替身。
|
||||
type orderRuntimeNotifierFake struct {
|
||||
// calls 记录发货通知调用次数。
|
||||
calls int
|
||||
}
|
||||
|
||||
// NotifyDelivery 记录一次发货通知调用。
|
||||
func (f *orderRuntimeNotifierFake) NotifyDelivery(string, string, string, string, string, string) {
|
||||
f.calls++
|
||||
}
|
||||
|
||||
// orderRuntimeMTopFake 是订单运行时测试使用的平台客户端替身。
|
||||
type orderRuntimeMTopFake struct {
|
||||
// consign 保存确认发货调用结果函数。
|
||||
@@ -51,6 +75,38 @@ func (f *orderRuntimeMTopFake) RefreshTokenWithDeviceIDContext(context.Context,
|
||||
return nil, errors.New("订单测试未预期令牌请求")
|
||||
}
|
||||
|
||||
// TestNewOrderRuntimeHooksUsesTypedOptionalServices 验证订单运行时依赖由 adapter typed port 统一转换并安全处理空依赖。
|
||||
func TestNewOrderRuntimeHooksUsesTypedOptionalServices(t *testing.T) {
|
||||
// emptyHooks 保存缺少可选服务时的回调集合。
|
||||
emptyHooks := NewOrderRuntimeHooks(nil, nil, nil, nil, nil, nil)
|
||||
if emptyHooks.AutomationReady() || emptyHooks.ClientAvailable() || emptyHooks.AccountRunning("missing") {
|
||||
t.Fatal("空依赖不应报告订单运行时能力可用")
|
||||
}
|
||||
// err 保存空自动化能力执行完整发货时返回的初始化错误。
|
||||
if _, err := emptyHooks.ManualFullDelivery(context.Background(), &orderapp.Order{}); err == nil {
|
||||
t.Fatal("空自动化依赖应返回错误")
|
||||
}
|
||||
emptyHooks.NotifyDelivery("cookie", "buyer", "item", "chat", "message")
|
||||
|
||||
// automation、notifier 保存 typed port 测试替身。
|
||||
automation := &orderRuntimeAutomationFake{}
|
||||
// notifier 保存记录通知调用次数的 typed port 测试替身。
|
||||
notifier := &orderRuntimeNotifierFake{}
|
||||
// hooks 保存已装配可选服务的订单运行时回调集合。
|
||||
hooks := NewOrderRuntimeHooks(nil, nil, automation, notifier, nil, nil)
|
||||
if hooks.AutomationReady() {
|
||||
t.Fatal("缺少账号 Manager 时不应报告完整自动化已就绪")
|
||||
}
|
||||
// sent、err 保存完整发货回调的发送数量和执行错误。
|
||||
if sent, err := hooks.ManualFullDelivery(context.Background(), &orderapp.Order{OrderID: "order-1"}); err != nil || sent != 2 || automation.calls != 1 {
|
||||
t.Fatalf("自动化回调未正确转发: sent=%d err=%v calls=%d", sent, err, automation.calls)
|
||||
}
|
||||
hooks.NotifyDelivery("cookie", "buyer", "item", "chat", "message")
|
||||
if notifier.calls != 1 {
|
||||
t.Fatalf("通知回调次数=%d,期望 1", notifier.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOrderRuntimeConfirmShipmentPersistsCookie 验证确认发货成功会写回平台返回的新 Cookie。
|
||||
func TestOrderRuntimeConfirmShipmentPersistsCookie(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库和资源清理函数。
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/qrlogin"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// MTOPClient 是平台装配边界使用的客户端别名,避免上层依赖具体 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)
|
||||
}
|
||||
|
||||
// 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{}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
// PlatformDependencies 保存 HTTP 应用装配所需的平台客户端;Server 只能通过本类型读取这些能力。
|
||||
// 旧的 Server 字段仅作为阶段性测试兼容入口保留,待所有调用方迁移后删除。
|
||||
type PlatformDependencies struct {
|
||||
// mtopClient 承担 MTOP 请求与订单、商品、账号资料等平台操作。
|
||||
mtopClient MTOPClient
|
||||
// longLoginClient 承担长登录状态查询、更新及响应 Cookie 返回。
|
||||
longLoginClient LongLoginClient
|
||||
// qrLoginService 承担二维码生成、状态轮询和风控验证完成。
|
||||
qrLoginService QRLoginService
|
||||
}
|
||||
|
||||
// NewPlatformDependencies 构造并校验平台客户端集合,拒绝半初始化依赖进入 Server。
|
||||
func NewPlatformDependencies(mtopClient MTOPClient, longLoginClient LongLoginClient, qrLoginService QRLoginService) (*PlatformDependencies, error) {
|
||||
if mtopClient == nil {
|
||||
return nil, errors.New("平台依赖 MTOP 客户端不能为空")
|
||||
}
|
||||
if longLoginClient == nil {
|
||||
return nil, errors.New("平台依赖长登录客户端不能为空")
|
||||
}
|
||||
if qrLoginService == nil {
|
||||
return nil, errors.New("平台依赖二维码服务不能为空")
|
||||
}
|
||||
return &PlatformDependencies{
|
||||
mtopClient: mtopClient,
|
||||
longLoginClient: longLoginClient,
|
||||
qrLoginService: qrLoginService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NewDefaultPlatformDependencies 创建生产环境使用的完整平台客户端集合。
|
||||
func NewDefaultPlatformDependencies(logger *slog.Logger) (*PlatformDependencies, error) {
|
||||
return NewPlatformDependencies(NewMTOPClient(), NewLongLoginClient(), NewQRLoginService(logger))
|
||||
}
|
||||
|
||||
// MTOPClient 返回已校验的 MTOP 客户端;返回值不含账号 Cookie 或其他敏感数据。
|
||||
func (d *PlatformDependencies) MTOPClient() MTOPClient {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return d.mtopClient
|
||||
}
|
||||
|
||||
// LongLoginClient 返回已校验的长登录客户端;调用方负责控制凭证读取和持久化范围。
|
||||
func (d *PlatformDependencies) LongLoginClient() LongLoginClient {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return d.longLoginClient
|
||||
}
|
||||
|
||||
// QRLoginService 返回已校验的二维码服务;平台会话状态仍由该服务自身负责生命周期。
|
||||
func (d *PlatformDependencies) QRLoginService() QRLoginService {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return d.qrLoginService
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// platformDependenciesQRFake 是平台依赖测试使用的二维码服务替身。
|
||||
type platformDependenciesQRFake struct{}
|
||||
|
||||
// GenerateQRCode 返回固定会话数据,验证依赖边界不会改写二维码协议。
|
||||
func (platformDependenciesQRFake) GenerateQRCode(context.Context) (string, string, error) {
|
||||
return "session", "https://example.test/qr", nil
|
||||
}
|
||||
|
||||
// GetSessionStatus 返回最小状态对象,验证二维码服务可以通过边界读取。
|
||||
func (platformDependenciesQRFake) GetSessionStatus(string) map[string]any {
|
||||
return map[string]any{"status": "waiting"}
|
||||
}
|
||||
|
||||
// CompleteVerification 返回固定验证结果,避免测试输出任何真实凭证。
|
||||
func (platformDependenciesQRFake) CompleteVerification(context.Context, string) (string, string, error) {
|
||||
return "masked-cookie", "account", nil
|
||||
}
|
||||
|
||||
// TestNewPlatformDependenciesRejectsIncomplete 验证平台依赖不得以半初始化状态进入 Server。
|
||||
func TestNewPlatformDependenciesRejectsIncomplete(t *testing.T) {
|
||||
// qrService 是测试使用的二维码能力替身。
|
||||
qrService := platformDependenciesQRFake{}
|
||||
// cases 保存每个缺失必需能力的构造场景和预期错误关键字。
|
||||
cases := []struct {
|
||||
name string
|
||||
mtop MTOPClient
|
||||
long LongLoginClient
|
||||
qr QRLoginService
|
||||
want string
|
||||
}{
|
||||
{name: "mtop", long: renew.Service{}, qr: qrService, want: "MTOP"},
|
||||
{name: "long_login", mtop: NewMTOPClient(), qr: qrService, want: "长登录"},
|
||||
{name: "qr_login", mtop: NewMTOPClient(), long: renew.Service{}, want: "二维码"},
|
||||
}
|
||||
// testCase 表示当前平台能力缺失场景,循环变量仅用于表格驱动测试。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// dependencies、err 保存本次构造结果及校验错误。
|
||||
dependencies, err := NewPlatformDependencies(testCase.mtop, testCase.long, testCase.qr)
|
||||
if err == nil || !strings.Contains(err.Error(), testCase.want) {
|
||||
t.Fatalf("NewPlatformDependencies error = %v, want substring %q", err, testCase.want)
|
||||
}
|
||||
if dependencies != nil {
|
||||
t.Fatalf("缺失依赖时不应返回平台依赖实例")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformDependenciesAccessorsExposeInjectedClients 验证访问器只返回构造时注入的客户端。
|
||||
func TestPlatformDependenciesAccessorsExposeInjectedClients(t *testing.T) {
|
||||
// mtopClient、longLoginClient 和 qrService 保存本测试注入的三个独立能力。
|
||||
mtopClient := NewMTOPClient()
|
||||
// longLoginClient 是本测试注入的长登录协议替身。
|
||||
longLoginClient := renew.Service{}
|
||||
// qrService 是本测试注入的二维码协议替身。
|
||||
qrService := platformDependenciesQRFake{}
|
||||
// dependencies、err 保存平台依赖边界及构造结果。
|
||||
dependencies, err := NewPlatformDependencies(mtopClient, longLoginClient, qrService)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPlatformDependencies: %v", err)
|
||||
}
|
||||
if dependencies.MTOPClient() != mtopClient {
|
||||
t.Fatalf("MTOPClient 未返回注入客户端")
|
||||
}
|
||||
if dependencies.LongLoginClient() != longLoginClient {
|
||||
t.Fatalf("LongLoginClient 未返回注入客户端")
|
||||
}
|
||||
if dependencies.QRLoginService() != qrService {
|
||||
t.Fatalf("QRLoginService 未返回注入客户端")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformDependenciesNilAccessors 验证 nil 接收者访问器安全返回 nil,便于错误路径诊断。
|
||||
func TestPlatformDependenciesNilAccessors(t *testing.T) {
|
||||
// dependencies 显式保持 nil,模拟 Server 构造前的平台依赖缺失。
|
||||
var dependencies *PlatformDependencies
|
||||
if dependencies.MTOPClient() != nil || dependencies.LongLoginClient() != nil || dependencies.QRLoginService() != nil {
|
||||
t.Fatalf("nil 平台依赖访问器必须返回 nil")
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
// SessionRecoveryHandler 是平台会话错误到账号恢复运行时的最小适配回调。
|
||||
// 回调只在确认错误属于 Session 失效时触发,调用方不会收到 Cookie 或 Token。
|
||||
type SessionRecoveryHandler func(context.Context, string, error) bool
|
||||
|
||||
// NewSessionRecoveryHandler 创建统一的平台会话恢复回调。
|
||||
// recoverFunc 只负责请求账号运行时恢复;本适配器负责识别平台错误和记录脱敏诊断。
|
||||
func NewSessionRecoveryHandler(logger *slog.Logger, recoverFunc func(context.Context, string) bool) SessionRecoveryHandler {
|
||||
return func(ctx context.Context, accountID string, err error) bool {
|
||||
if !IsSessionExpiredError(err) || recoverFunc == nil {
|
||||
return false
|
||||
}
|
||||
if logger != nil {
|
||||
logger.Warn("MTOP API 检测到 Session 过期,停止业务请求并开始即时续期", "account", accountID, "err", err)
|
||||
}
|
||||
return recoverFunc(ctx, accountID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSessionRecoveryHandlerFiltersNonExpiredErrors 验证普通平台错误不会触发账号恢复。
|
||||
func TestSessionRecoveryHandlerFiltersNonExpiredErrors(t *testing.T) {
|
||||
// calls 记录恢复端口被调用次数。
|
||||
calls := 0
|
||||
// handler 是绑定测试恢复端口的会话恢复适配器。
|
||||
handler := NewSessionRecoveryHandler(nil, func(context.Context, string) bool {
|
||||
calls++
|
||||
return true
|
||||
})
|
||||
// recovered 表示普通错误的恢复结果。
|
||||
recovered := handler(context.Background(), "acc1", errors.New("ordinary failure"))
|
||||
if recovered || calls != 0 {
|
||||
t.Fatalf("普通错误不应触发恢复: recovered=%v calls=%d", recovered, calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionRecoveryHandlerDelegatesExpiredErrors 验证 Session 失效只触发一次恢复端口。
|
||||
func TestSessionRecoveryHandlerDelegatesExpiredErrors(t *testing.T) {
|
||||
// calls 记录恢复端口被调用次数。
|
||||
calls := 0
|
||||
// handler 是绑定测试恢复端口的会话恢复适配器。
|
||||
handler := NewSessionRecoveryHandler(nil, func(_ context.Context, accountID string) bool {
|
||||
if accountID != "acc1" {
|
||||
t.Fatalf("恢复账号错误: %q", accountID)
|
||||
}
|
||||
calls++
|
||||
return true
|
||||
})
|
||||
// recovered 表示已识别 Session 失效后的恢复结果。
|
||||
recovered := handler(context.Background(), "acc1", errors.New("FAIL_SYS_SESSION_EXPIRED"))
|
||||
if !recovered || calls != 1 {
|
||||
t.Fatalf("Session 失效未正确委托: recovered=%v calls=%d", recovered, calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/reconciliation"
|
||||
)
|
||||
|
||||
// SystemDependencies 封装健康检查与订单补偿扫描所需的系统级适配器。
|
||||
type SystemDependencies struct {
|
||||
// store 保存系统适配器共享的数据库入口,仅在 adapter 内部使用。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// NewSystemDependencies 从数据库 Store 构造系统专用依赖组。
|
||||
func NewSystemDependencies(store *db.Store) *SystemDependencies {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
return &SystemDependencies{store: store}
|
||||
}
|
||||
|
||||
// NewDatabaseHealth 创建数据库健康检查适配器。
|
||||
func (d *SystemDependencies) NewDatabaseHealth() *DatabaseHealth {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewDatabaseHealth(d.store)
|
||||
}
|
||||
|
||||
// NewReconciliationService 创建外部发货成功后的本地补偿扫描服务。
|
||||
func (d *SystemDependencies) NewReconciliationService(logger *slog.Logger) *reconciliation.Service {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return reconciliation.New(d.store, logger)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package adapter
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestNewSystemDependenciesRejectsNilStore 确保系统级适配器不会在缺少数据库入口时构造成功。
|
||||
func TestNewSystemDependenciesRejectsNilStore(t *testing.T) {
|
||||
// dependencies 保存缺少 Store 时的系统依赖构造结果。
|
||||
dependencies := NewSystemDependencies(nil)
|
||||
if dependencies != nil {
|
||||
t.Fatal("缺少 Store 时不应返回系统依赖")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package adapter
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -31,3 +32,53 @@ func TestTransactionRepositoryRejectsMissingDependencies(t *testing.T) {
|
||||
t.Fatal("缺少事务工作函数时不应伪装成功")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTransactionRepositoryCommitsAndRollsBack 验证事务适配器提交成功操作并回滚失败操作。
|
||||
func TestTransactionRepositoryCommitsAndRollsBack(t *testing.T) {
|
||||
// database、dialect 和 openErr 保存最小 SQLite 数据库装配结果。
|
||||
database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/transaction-commit.db")
|
||||
if openErr != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", openErr)
|
||||
}
|
||||
defer database.Close()
|
||||
// repository 是当前测试使用的数据库事务适配器。
|
||||
repository := NewTransactionRepository(db.NewStore(database, dialect))
|
||||
// ctx 是本测试使用的背景上下文。
|
||||
ctx := context.Background()
|
||||
// createErr 表示创建事务测试表时的数据库错误。
|
||||
if _, createErr := database.ExecContext(ctx, `CREATE TABLE transaction_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil {
|
||||
t.Fatalf("创建事务测试表失败: %v", createErr)
|
||||
}
|
||||
// commitErr 表示成功事务的执行结果。
|
||||
commitErr := repository.WithTransaction(ctx, func(tx *sql.Tx) error {
|
||||
// execErr 表示事务内插入成功记录时的数据库错误。
|
||||
_, execErr := tx.ExecContext(ctx, `INSERT INTO transaction_probe (id, value) VALUES (1, 'committed')`)
|
||||
return execErr
|
||||
})
|
||||
if commitErr != nil {
|
||||
t.Fatalf("事务提交失败: %v", commitErr)
|
||||
}
|
||||
// rollbackErr 是故意返回的错误,用于验证事务不会提交部分写入。
|
||||
rollbackErr := errors.New("故意回滚")
|
||||
// returnedErr 表示回滚事务向调用方传播的错误。
|
||||
returnedErr := repository.WithTransaction(ctx, func(tx *sql.Tx) error {
|
||||
// execErr 表示事务内插入回滚记录时的数据库错误。
|
||||
_, execErr := tx.ExecContext(ctx, `INSERT INTO transaction_probe (id, value) VALUES (2, 'rolled back')`)
|
||||
if execErr != nil {
|
||||
return execErr
|
||||
}
|
||||
return rollbackErr
|
||||
})
|
||||
if !errors.Is(returnedErr, rollbackErr) {
|
||||
t.Fatalf("事务回滚错误不匹配: %v", returnedErr)
|
||||
}
|
||||
// count 是事务最终提交后测试表中的记录数。
|
||||
var count int
|
||||
// scanErr 表示读取事务测试表统计结果时的数据库错误。
|
||||
if scanErr := database.QueryRowContext(ctx, `SELECT COUNT(*) FROM transaction_probe`).Scan(&count); scanErr != nil {
|
||||
t.Fatalf("查询事务测试结果失败: %v", scanErr)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("事务回滚后记录数应为 1,got %d", count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package adapter
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestTypedDependenciesCoverServerAssembly 验证领域依赖组覆盖 Server 应用装配所需的全部基础设施边界。
|
||||
func TestTypedDependenciesCoverServerAssembly(t *testing.T) {
|
||||
// store、cleanup 保存测试用数据库聚合及其资源释放函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// orderDependencies 保存订单应用所需的显式依赖组。
|
||||
orderDependencies, orderErr := NewOrderDependencies(store)
|
||||
// accountDependencies 保存账号应用所需的显式依赖组。
|
||||
accountDependencies, accountErr := NewAccountDependencies(store)
|
||||
// itemDependencies 保存商品应用所需的显式依赖组。
|
||||
itemDependencies, itemErr := NewItemDependencies(store)
|
||||
// automationDependencies 保存自动化应用所需的显式依赖组。
|
||||
automationDependencies, automationErr := NewAutomationDependencies(store)
|
||||
// miscDependencies 保存通知、分析和卡券应用所需的显式依赖组。
|
||||
miscDependencies, miscErr := NewMiscDependencies(store)
|
||||
// chatDependencies 保存聊天应用所需的显式依赖组。
|
||||
chatDependencies := NewChatDependencies(store)
|
||||
// systemDependencies 保存系统健康检查和补偿扫描所需的显式依赖组。
|
||||
systemDependencies := NewSystemDependencies(store)
|
||||
// adminSettingsDependencies 保存管理员和设置应用所需的显式依赖组。
|
||||
adminSettingsDependencies := NewAdminSettingsDependencies(store)
|
||||
// platformDependencies 保存平台客户端和二维码能力所需的显式依赖组。
|
||||
platformDependencies, platformErr := NewDefaultPlatformDependencies(nil)
|
||||
if orderErr != nil || accountErr != nil || itemErr != nil || automationErr != nil || miscErr != nil || orderDependencies == nil || accountDependencies == nil || itemDependencies == nil || automationDependencies == nil || miscDependencies == nil || chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil || platformErr != nil || platformDependencies == nil {
|
||||
t.Fatalf("显式领域依赖组未完整覆盖 Server 装配: order=%v account=%v item=%v automation=%v misc=%v chat=%v system=%v admin=%v platform=%v", orderErr, accountErr, itemErr, automationErr, miscErr, chatDependencies != nil, systemDependencies != nil, adminSettingsDependencies != nil, platformErr)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user