阶段七:完成 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,72 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ErrCredentialRefreshInFlight 表示同一账号已有凭证恢复操作正在执行。
|
||||
var ErrCredentialRefreshInFlight = errors.New("账号凭证恢复正在执行")
|
||||
|
||||
// CredentialRefreshWork 执行一次账号凭证恢复;返回值表示是否已恢复可用凭证,错误保留底层失败原因。
|
||||
type CredentialRefreshWork func(context.Context) (bool, error)
|
||||
|
||||
// CredentialRefreshCoordinator 按账号串行化凭证恢复,保证慢速外部 I/O 不在锁内执行。
|
||||
// mu 只保护 inFlight;work 在释放协调状态后仍由调用方负责其自身凭证快照和提交边界。
|
||||
type CredentialRefreshCoordinator struct {
|
||||
// mu 保护 inFlight 的账号集合;持锁期间只做集合操作,不调用外部服务。
|
||||
mu sync.Mutex
|
||||
// inFlight 记录当前正在恢复的账号,任务结束、报错、取消或 panic 后必须移除。
|
||||
inFlight map[string]struct{}
|
||||
}
|
||||
|
||||
// NewCredentialRefreshCoordinator 创建空的账号凭证恢复协调器。
|
||||
func NewCredentialRefreshCoordinator() *CredentialRefreshCoordinator {
|
||||
return &CredentialRefreshCoordinator{inFlight: make(map[string]struct{})}
|
||||
}
|
||||
|
||||
// TryBegin 尝试登记账号恢复;成功时调用方必须在 defer 中执行 Finish,即使工作返回错误或 panic。
|
||||
func (c *CredentialRefreshCoordinator) TryBegin(accountID string) bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.inFlight == nil {
|
||||
c.inFlight = make(map[string]struct{})
|
||||
}
|
||||
// exists 表示该账号是否已有恢复工作登记,命中时拒绝并发外部续期。
|
||||
if _, exists := c.inFlight[accountID]; exists {
|
||||
return false
|
||||
}
|
||||
c.inFlight[accountID] = struct{}{}
|
||||
return true
|
||||
}
|
||||
|
||||
// Finish 清除账号恢复登记;重复调用保持幂等,便于兼容旧调用方的收尾路径。
|
||||
func (c *CredentialRefreshCoordinator) Finish(accountID string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.inFlight, accountID)
|
||||
}
|
||||
|
||||
// Run 在账号范围内执行一项恢复工作,并在所有返回路径后释放登记状态。
|
||||
// accepted 为 false 时表示已有同账号工作在执行;work 的错误和取消上下文由调用方继续记录。
|
||||
func (c *CredentialRefreshCoordinator) Run(ctx context.Context, accountID string, work CredentialRefreshWork) (accepted, renewed bool, err error) {
|
||||
if c == nil {
|
||||
return false, false, errors.New("账号凭证恢复协调器未初始化")
|
||||
}
|
||||
if !c.TryBegin(accountID) {
|
||||
return false, false, ErrCredentialRefreshInFlight
|
||||
}
|
||||
defer c.Finish(accountID)
|
||||
if work == nil {
|
||||
return true, false, errors.New("账号凭证恢复工作未提供")
|
||||
}
|
||||
renewed, err = work(ctx)
|
||||
return true, renewed, err
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCredentialRefreshCoordinatorSerializesSameAccount 验证同一账号只允许一个恢复回调运行。
|
||||
func TestCredentialRefreshCoordinatorSerializesSameAccount(t *testing.T) {
|
||||
// coordinator 保存待测试的账号恢复协调器。
|
||||
coordinator := NewCredentialRefreshCoordinator()
|
||||
// entered 用于让首个恢复回调保持执行状态。
|
||||
entered := make(chan struct{})
|
||||
// release 用于控制首个恢复回调何时完成。
|
||||
release := make(chan struct{})
|
||||
// firstDone 保存首个恢复调用的结果。
|
||||
firstDone := make(chan error, 1)
|
||||
go func() {
|
||||
// accepted、renewed、runErr 保存首个恢复回调的协调结果。
|
||||
// accepted、renewed、runErr 保存首个恢复回调的登记结果、凭证结果和错误。
|
||||
accepted, renewed, runErr := coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
return true, nil
|
||||
})
|
||||
if !accepted || !renewed {
|
||||
firstDone <- errors.New("首个恢复调用未成功登记")
|
||||
return
|
||||
}
|
||||
firstDone <- runErr
|
||||
}()
|
||||
<-entered
|
||||
// accepted、renewed、runErr 保存重复恢复调用的协调结果。
|
||||
accepted, renewed, runErr := coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
if accepted || renewed || !errors.Is(runErr, ErrCredentialRefreshInFlight) {
|
||||
t.Fatalf("重复恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr)
|
||||
}
|
||||
close(release)
|
||||
// runErr 保存首个恢复回调完成后的错误。
|
||||
if runErr := <-firstDone; runErr != nil {
|
||||
t.Fatalf("首个恢复错误: %v", runErr)
|
||||
}
|
||||
// accepted、renewed、runErr 保存首个调用结束后再次恢复的结果。
|
||||
accepted, renewed, runErr = coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
if !accepted || !renewed || runErr != nil {
|
||||
t.Fatalf("完成后恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCredentialRefreshCoordinatorReleasesOnErrorAndCancellation 验证错误与取消均不会遗留账号占用状态。
|
||||
func TestCredentialRefreshCoordinatorReleasesOnErrorAndCancellation(t *testing.T) {
|
||||
// coordinator 保存待测试的账号恢复协调器。
|
||||
coordinator := NewCredentialRefreshCoordinator()
|
||||
// expectedErr 保存恢复回调预置的业务错误。
|
||||
expectedErr := errors.New("renew failed")
|
||||
// accepted、renewed、runErr 保存错误恢复回调的协调结果。
|
||||
accepted, renewed, runErr := coordinator.Run(context.Background(), "account-2", func(context.Context) (bool, error) {
|
||||
return false, expectedErr
|
||||
})
|
||||
if !accepted || renewed || !errors.Is(runErr, expectedErr) {
|
||||
t.Fatalf("错误恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr)
|
||||
}
|
||||
// canceled、cancel 保存已取消的恢复上下文及其释放函数。
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
// accepted、renewed、runErr 保存取消恢复回调的协调结果。
|
||||
accepted, renewed, runErr = coordinator.Run(canceled, "account-2", func(ctx context.Context) (bool, error) {
|
||||
return false, ctx.Err()
|
||||
})
|
||||
if !accepted || renewed || !errors.Is(runErr, context.Canceled) {
|
||||
t.Fatalf("取消恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCredentialRefreshCoordinatorReleasesAfterPanic 验证回调 panic 仍会释放账号登记状态。
|
||||
func TestCredentialRefreshCoordinatorReleasesAfterPanic(t *testing.T) {
|
||||
// coordinator 保存待测试的账号恢复协调器。
|
||||
coordinator := NewCredentialRefreshCoordinator()
|
||||
// panicked 标记是否捕获到预期 panic。
|
||||
panicked := false
|
||||
func() {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
panicked = true
|
||||
}
|
||||
}()
|
||||
coordinator.Run(context.Background(), "account-3", func(context.Context) (bool, error) {
|
||||
panic("test panic")
|
||||
})
|
||||
}()
|
||||
if !panicked {
|
||||
t.Fatal("恢复回调 panic 应向调用方传播")
|
||||
}
|
||||
// accepted、renewed、runErr 保存 panic 后重新执行的结果。
|
||||
accepted, renewed, runErr := coordinator.Run(context.Background(), "account-3", func(context.Context) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
if !accepted || !renewed || runErr != nil {
|
||||
t.Fatalf("panic 后恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCredentialRefreshCoordinatorSupportsConcurrentDifferentAccounts 验证不同账号可以并行恢复且不共享占用状态。
|
||||
func TestCredentialRefreshCoordinatorSupportsConcurrentDifferentAccounts(t *testing.T) {
|
||||
// coordinator 保存待测试的账号恢复协调器。
|
||||
coordinator := NewCredentialRefreshCoordinator()
|
||||
// start 用于同步两个账号的回调开始时机。
|
||||
start := make(chan struct{})
|
||||
// results 保存两个账号恢复调用的结果。
|
||||
results := make(chan error, 2)
|
||||
// waitGroup 等待两个独立账号的恢复调用结束。
|
||||
var waitGroup sync.WaitGroup
|
||||
waitGroup.Add(2)
|
||||
// accountID 表示当前并行恢复测试正在处理的账号标识。
|
||||
for _, accountID := range []string{"account-4", "account-5"} {
|
||||
// currentAccount 保存当前并行恢复的账号标识。
|
||||
currentAccount := accountID
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
// accepted、renewed、runErr 保存当前账号恢复结果。
|
||||
accepted, renewed, runErr := coordinator.Run(context.Background(), currentAccount, func(context.Context) (bool, error) {
|
||||
<-start
|
||||
return true, nil
|
||||
})
|
||||
if !accepted || !renewed {
|
||||
results <- errors.New("独立账号未成功恢复")
|
||||
return
|
||||
}
|
||||
results <- runErr
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
for range 2 {
|
||||
// runErr 保存并行账号恢复回调的错误。
|
||||
if runErr := <-results; runErr != nil {
|
||||
t.Fatalf("并行恢复错误: %v", runErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,3 +43,10 @@ type CredentialRepository interface {
|
||||
// UpdateProfile 保存不含凭证的账号展示资料。
|
||||
UpdateProfile(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
// CredentialSessionPort 定义平台响应 Cookie 会话写回所需的最小凭证端口。
|
||||
// 该端口不包含账号查询、锁管理或登录秘密方法,调用方必须在外层完成凭证锁和快照复核。
|
||||
type CredentialSessionPort interface {
|
||||
// UpdateRenewalCookie 保存平台返回的 Cookie 与 metadata;明文仅在适配器内短暂存在。
|
||||
UpdateRenewalCookie(context.Context, string, string, string, int64) error
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package account
|
||||
|
||||
import "context"
|
||||
|
||||
// LoginStatusPort 定义登录成功后判断账号是否启用所需的最小状态查询能力。
|
||||
type LoginStatusPort interface {
|
||||
// GetStatus 返回账号当前是否启用;该查询不读取或解密凭证内容。
|
||||
GetStatus(context.Context, string) bool
|
||||
}
|
||||
|
||||
// LoginRestartPort 定义登录成功后重启账号运行时所需的最小能力。
|
||||
type LoginRestartPort interface {
|
||||
// Restart 使用刚写入的持久化凭证重启账号运行实例。
|
||||
Restart(context.Context, string) error
|
||||
}
|
||||
|
||||
// LoginSuccessService 编排登录成功后的资料刷新与运行时重启,不依赖 HTTP 或 Server。
|
||||
type LoginSuccessService struct {
|
||||
// summaries 提供不含秘密的账号归属确认能力。
|
||||
summaries ProfileSummaryRepository
|
||||
// profile 负责平台资料刷新和本地资料持久化。
|
||||
profile *ProfileService
|
||||
// statuses 提供账号启用状态查询能力。
|
||||
statuses LoginStatusPort
|
||||
// runtime 提供账号运行时重启能力。
|
||||
runtime LoginRestartPort
|
||||
// report 记录不含凭证的后续动作错误;为空时忽略诊断。
|
||||
report func(string, error)
|
||||
}
|
||||
|
||||
// NewLoginSuccessService 构造登录成功后的应用编排服务。
|
||||
func NewLoginSuccessService(summaries ProfileSummaryRepository, profile *ProfileService, statuses LoginStatusPort, runtime LoginRestartPort, report func(string, error)) *LoginSuccessService {
|
||||
return &LoginSuccessService{summaries: summaries, profile: profile, statuses: statuses, runtime: runtime, report: report}
|
||||
}
|
||||
|
||||
// AfterSuccessfulLogin 在凭证锁释放后刷新资料并按账号启用状态重启运行时。
|
||||
func (s *LoginSuccessService) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.summaries != nil {
|
||||
// summaryErr 保存登录成功后归属摘要复核错误;失败时跳过资料刷新但不阻断重启。
|
||||
_, summaryErr := s.summaries.GetOwnedSummary(ctx, userID, accountID)
|
||||
if summaryErr == nil && s.profile != nil {
|
||||
// result 和 profileErr 保存资料刷新结果及基础设施错误。
|
||||
result, profileErr := s.profile.RefreshProfile(ctx, userID, accountID)
|
||||
if profileErr != nil {
|
||||
s.reportError("登录后刷新账号资料失败", profileErr)
|
||||
} else if result.ErrorMessage != "" {
|
||||
s.reportError("登录后刷新账号资料返回业务错误", nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.statuses != nil && s.statuses.GetStatus(ctx, accountID) && s.runtime != nil {
|
||||
// restartErr 保存登录成功后运行时重启错误。
|
||||
if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil {
|
||||
s.reportError("账号登录后重启账号失败", restartErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reportError 统一传递登录成功后续动作的脱敏诊断。
|
||||
func (s *LoginSuccessService) reportError(message string, err error) {
|
||||
if s.report != nil {
|
||||
s.report(message, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// loginSuccessStatusFake 保存登录成功编排测试中的启用状态。
|
||||
type loginSuccessStatusFake struct{ enabled bool }
|
||||
|
||||
// GetStatus 返回测试账号启用状态。
|
||||
func (f loginSuccessStatusFake) GetStatus(context.Context, string) bool { return f.enabled }
|
||||
|
||||
// loginSuccessRuntimeFake 记录登录成功后的重启请求。
|
||||
type loginSuccessRuntimeFake struct{ restarts int }
|
||||
|
||||
// Restart 记录一次账号运行时重启。
|
||||
func (f *loginSuccessRuntimeFake) Restart(context.Context, string) error {
|
||||
f.restarts++
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestLoginSuccessServiceSkipsMissingOptionalPorts 验证缺少可选后续端口时不产生副作用。
|
||||
func TestLoginSuccessServiceSkipsMissingOptionalPorts(t *testing.T) {
|
||||
// service 保存未装配后续端口的登录成功服务。
|
||||
service := NewLoginSuccessService(nil, nil, nil, nil, nil)
|
||||
service.AfterSuccessfulLogin(context.Background(), 1, "account")
|
||||
}
|
||||
|
||||
// TestLoginSuccessServiceRestartsEnabledAccount 验证登录成功后仅对启用账号触发运行时重启。
|
||||
func TestLoginSuccessServiceRestartsEnabledAccount(t *testing.T) {
|
||||
// runtime 保存登录成功后重启调用的测试端口。
|
||||
runtime := &loginSuccessRuntimeFake{}
|
||||
// service 保存启用账号的登录成功编排服务。
|
||||
service := NewLoginSuccessService(nil, nil, loginSuccessStatusFake{enabled: true}, runtime, nil)
|
||||
service.AfterSuccessfulLogin(context.Background(), 1, "account")
|
||||
if runtime.restarts != 1 {
|
||||
t.Fatalf("restarts=%d", runtime.restarts)
|
||||
}
|
||||
// disabledRuntime 保存停用账号使用的独立运行时端口。
|
||||
disabledRuntime := &loginSuccessRuntimeFake{}
|
||||
// disabledService 保存停用账号的登录成功编排服务。
|
||||
disabledService := NewLoginSuccessService(nil, nil, loginSuccessStatusFake{}, disabledRuntime, nil)
|
||||
disabledService.AfterSuccessfulLogin(context.Background(), 1, "account")
|
||||
if disabledRuntime.restarts != 0 {
|
||||
t.Fatalf("disabled account restarts=%d", disabledRuntime.restarts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrCredentialEmpty 表示账号存在但没有可供平台调用的 Cookie。
|
||||
var ErrCredentialEmpty = errors.New("账号 Cookie 为空")
|
||||
|
||||
// PlatformCredentialViewPort 定义读取平台调用窄凭证视图的最小消费者端口。
|
||||
// 实现方负责数据库查询与解密;调用方不得把返回的明文写入摘要、日志或 HTTP DTO。
|
||||
type PlatformCredentialViewPort interface {
|
||||
// LoadPlatformDetail 读取指定账号的平台 Cookie 视图,不读取登录密码。
|
||||
LoadPlatformDetail(context.Context, string) (*CredentialDetail, error)
|
||||
}
|
||||
|
||||
// PlatformCredentialService 编排平台凭证窄视图读取和当前用户归属复核。
|
||||
// 该服务只在确有平台调用需要时返回 Cookie 明文,普通所有权检查不会返回敏感值。
|
||||
type PlatformCredentialService struct {
|
||||
// port 保存由适配器实现的平台凭证读取端口;服务本身不依赖数据库类型。
|
||||
port PlatformCredentialViewPort
|
||||
}
|
||||
|
||||
// NewPlatformCredentialService 构造平台凭证只读应用服务并校验端口。
|
||||
func NewPlatformCredentialService(port PlatformCredentialViewPort) (*PlatformCredentialService, error) {
|
||||
if port == nil {
|
||||
return nil, errors.New("平台凭证读取端口未初始化")
|
||||
}
|
||||
return &PlatformCredentialService{port: port}, nil
|
||||
}
|
||||
|
||||
// LoadPlatformDetail 读取平台运行所需的窄视图;登录密码不会进入该调用链。
|
||||
func (s *PlatformCredentialService) LoadPlatformDetail(ctx context.Context, accountID string) (*CredentialDetail, error) {
|
||||
if s == nil || s.port == nil {
|
||||
return nil, errors.New("平台凭证读取服务未初始化")
|
||||
}
|
||||
return s.port.LoadPlatformDetail(ctx, accountID)
|
||||
}
|
||||
|
||||
// ValidateOwned 验证平台账号归属和 Cookie 可用性,只返回非敏感用户标识。
|
||||
func (s *PlatformCredentialService) ValidateOwned(ctx context.Context, userID int64, accountID string) (int64, error) {
|
||||
// detail、loadErr 保存平台凭证窄视图及其读取错误;Cookie 只在本方法内部用于可用性判断。
|
||||
detail, loadErr := s.LoadPlatformDetail(ctx, accountID)
|
||||
if loadErr != nil {
|
||||
return 0, loadErr
|
||||
}
|
||||
if detail == nil || detail.ID == "" || detail.UserID == 0 {
|
||||
return 0, ErrCredentialNotFound
|
||||
}
|
||||
if detail.UserID != userID {
|
||||
return 0, ErrForbidden
|
||||
}
|
||||
if detail.Value == "" {
|
||||
return 0, ErrCredentialEmpty
|
||||
}
|
||||
return detail.UserID, nil
|
||||
}
|
||||
|
||||
// LoadOwnedValue 读取已通过所有权复核的 Cookie 明文;返回值只用于当前平台请求。
|
||||
func (s *PlatformCredentialService) LoadOwnedValue(ctx context.Context, userID int64, accountID string) (string, error) {
|
||||
// detail、loadErr 保存所有权复核使用的平台凭证视图及其读取错误。
|
||||
detail, loadErr := s.LoadPlatformDetail(ctx, accountID)
|
||||
if loadErr != nil {
|
||||
return "", loadErr
|
||||
}
|
||||
if detail == nil || detail.ID == "" || detail.UserID == 0 {
|
||||
return "", ErrCredentialNotFound
|
||||
}
|
||||
if detail.UserID != userID {
|
||||
return "", ErrCredentialNotFound
|
||||
}
|
||||
if detail.Value == "" {
|
||||
return "", ErrCredentialEmpty
|
||||
}
|
||||
return detail.Value, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// platformCredentialPortFake 保存测试用平台凭证窄视图,不模拟数据库或加密实现。
|
||||
type platformCredentialPortFake struct {
|
||||
// detail 是端口返回的最小平台凭证视图。
|
||||
detail *CredentialDetail
|
||||
// err 是端口返回的读取错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// TestNewPlatformCredentialServiceRejectsMissingPort 验证凭证读取服务不会接受半初始化端口。
|
||||
func TestNewPlatformCredentialServiceRejectsMissingPort(t *testing.T) {
|
||||
// service、serviceErr 保存缺失端口时的构造结果。
|
||||
service, serviceErr := NewPlatformCredentialService(nil)
|
||||
if service != nil || serviceErr == nil {
|
||||
t.Fatalf("缺失凭证端口不应构造成功: service=%v err=%v", service, serviceErr)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadPlatformDetail 返回固定平台凭证视图,验证应用服务不要求数据库具体类型。
|
||||
func (f platformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*CredentialDetail, error) {
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
// TestPlatformCredentialServiceValidatesOwnedWithoutReturningCookie 验证归属校验只返回用户标识。
|
||||
func TestPlatformCredentialServiceValidatesOwnedWithoutReturningCookie(t *testing.T) {
|
||||
// service 是使用最小凭证端口构造的平台凭证应用服务。
|
||||
service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{detail: &CredentialDetail{ID: "acc1", UserID: 7, Value: "sid=masked"}})
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// ownerID、validationErr 保存归属校验的非敏感结果及错误。
|
||||
ownerID, validationErr := service.ValidateOwned(context.Background(), 7, "acc1")
|
||||
if validationErr != nil || ownerID != 7 {
|
||||
t.Fatalf("归属校验结果异常: owner=%d err=%v", ownerID, validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformCredentialServiceRejectsForeignAndEmptyCredentials 验证越权和空 Cookie 均 fail closed。
|
||||
func TestPlatformCredentialServiceRejectsForeignAndEmptyCredentials(t *testing.T) {
|
||||
// cases 描述不同平台凭证状态及期望的稳定应用错误。
|
||||
cases := []struct {
|
||||
name string
|
||||
detail *CredentialDetail
|
||||
want error
|
||||
}{
|
||||
{name: "foreign", detail: &CredentialDetail{ID: "acc1", UserID: 8, Value: "sid=masked"}, want: ErrForbidden},
|
||||
{name: "empty", detail: &CredentialDetail{ID: "acc1", UserID: 7}, want: ErrCredentialEmpty},
|
||||
}
|
||||
// testCase 表示当前遍历的平台凭证状态用例。
|
||||
// testCase 表示当前遍历的凭证状态与预期错误。
|
||||
for _, testCase := range cases {
|
||||
// testCase 是当前凭证状态用例,防止闭包捕获后续迭代变量。
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// service 是当前状态用例使用的平台凭证应用服务。
|
||||
service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{detail: testCase.detail})
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// _, validationErr 保存归属校验错误;明文结果不会被测试输出。
|
||||
_, validationErr := service.ValidateOwned(context.Background(), 7, "acc1")
|
||||
if !errors.Is(validationErr, testCase.want) {
|
||||
t.Fatalf("错误类型=%v,期望=%v", validationErr, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlatformCredentialServicePropagatesPortErrors 验证基础设施错误不会被伪装成成功。
|
||||
func TestPlatformCredentialServicePropagatesPortErrors(t *testing.T) {
|
||||
// portErr 是模拟凭证存储不可用的脱敏错误。
|
||||
portErr := errors.New("credential store unavailable")
|
||||
// service 是绑定故障端口的平台凭证应用服务。
|
||||
service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{err: portErr})
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造凭证服务失败: %v", serviceErr)
|
||||
}
|
||||
// _, loadErr 保存平台凭证读取错误。
|
||||
_, loadErr := service.LoadPlatformDetail(context.Background(), "acc1")
|
||||
if !errors.Is(loadErr, portErr) {
|
||||
t.Fatalf("错误未透传: %v", loadErr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrQRLoginSessionNotFound 表示扫码会话不存在或已经超过服务端保留期限。
|
||||
var ErrQRLoginSessionNotFound = errors.New("扫码会话不存在或已过期")
|
||||
|
||||
// ErrQRLoginSessionForbidden 表示当前用户不是扫码会话的创建者。
|
||||
var ErrQRLoginSessionForbidden = errors.New("扫码会话不属于当前用户")
|
||||
|
||||
// QRLoginSessionPersistence 是扫码成功后缓存的非敏感持久化结果,避免重复写入账号凭证。
|
||||
type QRLoginSessionPersistence struct {
|
||||
// AccountID 是扫码结果最终写入的本地账号标识。
|
||||
AccountID string
|
||||
// IsNew 表示本次扫码是否创建了新的本地账号。
|
||||
IsNew bool
|
||||
// UserID 是创建该扫码会话的本地用户标识,用于阻止跨用户复用幂等结果。
|
||||
UserID int64
|
||||
// CreatedAt 是结果写入缓存的时间,仅用于诊断和生命周期观测。
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// QRLoginSessionRegistry 持有扫码会话所有权和幂等结果,Server 只通过方法访问这些状态。
|
||||
// mu 保护 owners 与 persisted;persistLocks 为每个会话串行化慢速凭证写入,锁内禁止持有 mu 调用外部 I/O。
|
||||
type QRLoginSessionRegistry struct {
|
||||
mu sync.Mutex
|
||||
owners map[string]qrLoginSessionOwner
|
||||
persisted map[string]QRLoginSessionPersistence
|
||||
persistLocks map[string]*qrLoginPersistenceLock
|
||||
ownerLifetime time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// qrLoginSessionOwner 保存扫码会话创建者和创建时间,不包含 Cookie 或平台 Token。
|
||||
type qrLoginSessionOwner struct {
|
||||
// userID 是创建扫码会话的本地用户标识。
|
||||
userID int64
|
||||
// createdAt 是会话创建时间,用于服务端过期回收。
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
// qrLoginPersistenceLock 保存单个扫码会话的串行锁及等待者计数,用于安全回收锁对象。
|
||||
type qrLoginPersistenceLock struct {
|
||||
// mu 串行化该会话的凭证持久化回调;不与注册表主锁同时持有。
|
||||
mu sync.Mutex
|
||||
// refs 统计已经取得该锁或正在等待该锁的调用数,避免回收时制造第二把锁。
|
||||
refs int
|
||||
}
|
||||
|
||||
// NewQRLoginSessionRegistry 创建扫码会话状态注册表,并设置默认三十分钟的 HTTP 所有权期限。
|
||||
func NewQRLoginSessionRegistry() *QRLoginSessionRegistry {
|
||||
return &QRLoginSessionRegistry{
|
||||
owners: make(map[string]qrLoginSessionOwner),
|
||||
persisted: make(map[string]QRLoginSessionPersistence),
|
||||
persistLocks: make(map[string]*qrLoginPersistenceLock),
|
||||
ownerLifetime: 30 * time.Minute,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// Register 记录新扫码会话的创建者;重复会话标识会覆盖旧所有权,平台层负责保证标识唯一。
|
||||
func (r *QRLoginSessionRegistry) Register(sessionID string, userID int64, createdAt time.Time) {
|
||||
if r == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
if createdAt.IsZero() {
|
||||
createdAt = r.currentTime()
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.owners == nil {
|
||||
r.owners = make(map[string]qrLoginSessionOwner)
|
||||
}
|
||||
r.owners[sessionID] = qrLoginSessionOwner{userID: userID, createdAt: createdAt}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// Authorize 校验扫码会话归属;过期或不存在统一返回 NotFound,归属不符返回 Forbidden。
|
||||
func (r *QRLoginSessionRegistry) Authorize(sessionID string, userID int64) error {
|
||||
if r == nil || sessionID == "" {
|
||||
return ErrQRLoginSessionNotFound
|
||||
}
|
||||
r.mu.Lock()
|
||||
// owner 保存会话创建者;ok 表示注册表中存在该会话。
|
||||
owner, ok := r.owners[sessionID]
|
||||
// expired 表示会话创建时间已经超过 HTTP 所有权期限。
|
||||
expired := ok && owner.createdAt.Before(r.currentTime().Add(-r.ownerLifetime))
|
||||
if expired {
|
||||
delete(r.owners, sessionID)
|
||||
r.deletePersistedLocked(sessionID)
|
||||
r.deletePersistLockIfIdleLocked(sessionID)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if !ok || expired {
|
||||
return ErrQRLoginSessionNotFound
|
||||
}
|
||||
if owner.userID != userID {
|
||||
return ErrQRLoginSessionForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cleanup 删除超过所有权期限的会话并返回应同步释放的平台会话标识。
|
||||
func (r *QRLoginSessionRegistry) Cleanup(now time.Time) []string {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if now.IsZero() {
|
||||
now = r.currentTime()
|
||||
}
|
||||
// cutoff 是本次清理允许保留的最早会话创建时间。
|
||||
cutoff := now.Add(-r.ownerLifetime)
|
||||
// expired 收集需要同步释放的平台扫码会话标识。
|
||||
expired := make([]string, 0)
|
||||
r.mu.Lock()
|
||||
// sessionID、owner 分别表示当前遍历的扫码会话标识及其创建者记录。
|
||||
for sessionID, owner := range r.owners {
|
||||
if owner.createdAt.Before(cutoff) {
|
||||
delete(r.owners, sessionID)
|
||||
r.deletePersistedLocked(sessionID)
|
||||
r.deletePersistLockIfIdleLocked(sessionID)
|
||||
expired = append(expired, sessionID)
|
||||
}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return expired
|
||||
}
|
||||
|
||||
// Delete 移除指定扫码会话的所有权和幂等结果;平台会话释放由调用方按返回标识执行。
|
||||
func (r *QRLoginSessionRegistry) Delete(sessionID string) {
|
||||
if r == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
delete(r.owners, sessionID)
|
||||
r.deletePersistedLocked(sessionID)
|
||||
r.deletePersistLockIfIdleLocked(sessionID)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// PersistOnce 以会话为粒度串行执行凭证持久化,并缓存成功后的非敏感结果。
|
||||
// work 仅在该会话锁内执行,不能把 Cookie 写入注册表或日志;失败不会留下幂等结果。
|
||||
func (r *QRLoginSessionRegistry) PersistOnce(sessionID string, userID int64, work func() (QRLoginSessionPersistence, error)) (QRLoginSessionPersistence, error) {
|
||||
if r == nil || sessionID == "" || work == nil {
|
||||
return QRLoginSessionPersistence{}, errors.New("扫码会话注册表未初始化")
|
||||
}
|
||||
// persistLock 串行化同一扫码会话的慢速凭证写入,避免重复创建账号。
|
||||
persistLock := r.acquirePersistLock(sessionID)
|
||||
persistLock.mu.Lock()
|
||||
defer r.releasePersistLock(sessionID, persistLock)
|
||||
|
||||
r.mu.Lock()
|
||||
// persisted、ok 保存已完成的幂等结果及其存在性。
|
||||
if persisted, ok := r.persisted[sessionID]; ok {
|
||||
r.mu.Unlock()
|
||||
if persisted.UserID != userID {
|
||||
return QRLoginSessionPersistence{}, ErrQRLoginSessionForbidden
|
||||
}
|
||||
return persisted, nil
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
// persisted 保存工作函数返回的非敏感结果;Cookie 明文只在 work 的调用链内短暂存在。
|
||||
persisted, err := work()
|
||||
if err != nil {
|
||||
return QRLoginSessionPersistence{}, err
|
||||
}
|
||||
persisted.UserID = userID
|
||||
if persisted.CreatedAt.IsZero() {
|
||||
persisted.CreatedAt = r.currentTime()
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.persisted == nil {
|
||||
r.persisted = make(map[string]QRLoginSessionPersistence)
|
||||
}
|
||||
r.persisted[sessionID] = persisted
|
||||
r.mu.Unlock()
|
||||
return persisted, nil
|
||||
}
|
||||
|
||||
// currentTime 返回可测试的当前时间;测试可在包内替换 now 而不影响生产时钟。
|
||||
func (r *QRLoginSessionRegistry) currentTime() time.Time {
|
||||
if r != nil && r.now != nil {
|
||||
return r.now().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// acquirePersistLock 获取会话级持久化锁,并在注册表主锁内登记等待者数量。
|
||||
func (r *QRLoginSessionRegistry) acquirePersistLock(sessionID string) *qrLoginPersistenceLock {
|
||||
r.mu.Lock()
|
||||
if r.persistLocks == nil {
|
||||
r.persistLocks = make(map[string]*qrLoginPersistenceLock)
|
||||
}
|
||||
// persistLock 保存该会话共享的锁对象,所有等待者都复用同一实例。
|
||||
persistLock := r.persistLocks[sessionID]
|
||||
if persistLock == nil {
|
||||
persistLock = &qrLoginPersistenceLock{}
|
||||
r.persistLocks[sessionID] = persistLock
|
||||
}
|
||||
persistLock.refs++
|
||||
r.mu.Unlock()
|
||||
return persistLock
|
||||
}
|
||||
|
||||
// releasePersistLock 释放会话级持久化锁,并在没有等待者时回收锁对象。
|
||||
func (r *QRLoginSessionRegistry) releasePersistLock(sessionID string, persistLock *qrLoginPersistenceLock) {
|
||||
persistLock.mu.Unlock()
|
||||
r.mu.Lock()
|
||||
persistLock.refs--
|
||||
if persistLock.refs == 0 && r.persistLocks[sessionID] == persistLock {
|
||||
delete(r.persistLocks, sessionID)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// deletePersistLockIfIdleLocked 在调用方持有注册表主锁时回收没有并发等待者的锁对象。
|
||||
func (r *QRLoginSessionRegistry) deletePersistLockIfIdleLocked(sessionID string) {
|
||||
// persistLock 保存待回收的会话级锁对象;调用方已持有注册表主锁。
|
||||
persistLock := r.persistLocks[sessionID]
|
||||
if persistLock != nil && persistLock.refs == 0 {
|
||||
delete(r.persistLocks, sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
// deletePersistedLocked 删除会话缓存;调用方必须已经持有 mu。
|
||||
func (r *QRLoginSessionRegistry) deletePersistedLocked(sessionID string) {
|
||||
delete(r.persisted, sessionID)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestQRLoginSessionRegistryAuthorizesAndExpires 验证扫码会话所有权校验和过期回收不暴露凭证状态。
|
||||
func TestQRLoginSessionRegistryAuthorizesAndExpires(t *testing.T) {
|
||||
// now 固定测试时钟,使会话生命周期断言不依赖真实墙钟。
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
// registry 保存当前测试的扫码会话状态。
|
||||
registry := NewQRLoginSessionRegistry()
|
||||
registry.now = func() time.Time { return now }
|
||||
registry.Register("session-1", 7, now)
|
||||
// err 保存会话所有者访问校验结果。
|
||||
if err := registry.Authorize("session-1", 7); err != nil {
|
||||
t.Fatalf("会话所有者应能访问: %v", err)
|
||||
}
|
||||
if !errors.Is(registry.Authorize("session-1", 8), ErrQRLoginSessionForbidden) {
|
||||
t.Fatal("其他用户访问会话应被拒绝")
|
||||
}
|
||||
now = now.Add(31 * time.Minute)
|
||||
// err 保存过期会话访问校验结果。
|
||||
if !errors.Is(registry.Authorize("session-1", 7), ErrQRLoginSessionNotFound) {
|
||||
t.Fatal("过期会话应视为不存在")
|
||||
}
|
||||
// got 保存重复清理返回的平台会话标识列表。
|
||||
if got := registry.Cleanup(now); len(got) != 0 {
|
||||
t.Fatalf("过期会话已在授权检查中清理,不应重复返回: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginSessionRegistryCleanupReturnsPlatformSessions 验证批量清理返回需要释放的平台会话标识。
|
||||
func TestQRLoginSessionRegistryCleanupReturnsPlatformSessions(t *testing.T) {
|
||||
// now 固定测试时钟并构造一个已经超时的会话。
|
||||
now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
// registry 保存当前测试的扫码会话状态。
|
||||
registry := NewQRLoginSessionRegistry()
|
||||
registry.now = func() time.Time { return now }
|
||||
registry.Register("expired", 7, now.Add(-31*time.Minute))
|
||||
registry.Register("active", 7, now)
|
||||
// expired 保存注册表报告的过期平台会话标识。
|
||||
expired := registry.Cleanup(now)
|
||||
if len(expired) != 1 || expired[0] != "expired" {
|
||||
t.Fatalf("过期会话列表异常: %v", expired)
|
||||
}
|
||||
// err 保存活动会话访问校验结果。
|
||||
if err := registry.Authorize("active", 7); err != nil {
|
||||
t.Fatalf("活动会话不应被清理: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginSessionRegistryPersistOnceIsIdempotent 验证同一扫码会话并发持久化只执行一次工作函数。
|
||||
func TestQRLoginSessionRegistryPersistOnceIsIdempotent(t *testing.T) {
|
||||
// registry 保存当前测试的扫码会话状态。
|
||||
registry := NewQRLoginSessionRegistry()
|
||||
// workCalls 统计慢速持久化工作函数被实际执行的次数。
|
||||
workCalls := 0
|
||||
// workMu 保护测试计数器,避免并发断言产生数据竞争。
|
||||
var workMu sync.Mutex
|
||||
// work 模拟应用层凭证写入并只返回非敏感结果。
|
||||
work := func() (QRLoginSessionPersistence, error) {
|
||||
workMu.Lock()
|
||||
workCalls++
|
||||
workMu.Unlock()
|
||||
time.Sleep(time.Millisecond)
|
||||
return QRLoginSessionPersistence{AccountID: "account-1", IsNew: true}, nil
|
||||
}
|
||||
// results 保存两个并发调用得到的幂等结果。
|
||||
results := make([]QRLoginSessionPersistence, 2)
|
||||
// errs 保存两个并发调用的错误结果。
|
||||
errs := make([]error, 2)
|
||||
// waitGroup 等待两个并发持久化调用结束。
|
||||
var waitGroup sync.WaitGroup
|
||||
waitGroup.Add(2)
|
||||
// index 表示当前并发持久化调用在测试结果数组中的位置。
|
||||
for index := range results {
|
||||
go func(index int) {
|
||||
defer waitGroup.Done()
|
||||
results[index], errs[index] = registry.PersistOnce("session-1", 7, work)
|
||||
}(index)
|
||||
}
|
||||
waitGroup.Wait()
|
||||
if workCalls != 1 {
|
||||
t.Fatalf("同一会话工作函数执行次数=%d,期望 1", workCalls)
|
||||
}
|
||||
// index、err 分别表示当前并发调用下标及其错误结果。
|
||||
for index, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("并发调用 %d 失败: %v", index, err)
|
||||
}
|
||||
if results[index].AccountID != "account-1" || !results[index].IsNew {
|
||||
t.Fatalf("并发调用 %d 返回结果异常: %+v", index, results[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RuntimeStatus 是账号运行时对外提供的非持久化连接状态快照;不包含 Cookie、Token 或其他凭证。
|
||||
type RuntimeStatus struct {
|
||||
// State 是运行时状态机当前状态,例如 online、error 或 auth_expired。
|
||||
State string `json:"state"`
|
||||
// Message 是面向管理页面的非敏感诊断信息。
|
||||
Message string `json:"message,omitempty"`
|
||||
// Connected 表示当前账号是否仍有可用的实时连接。
|
||||
Connected bool `json:"connected"`
|
||||
// Failures 是最近连接失败次数,具体统计窗口由运行时实现决定。
|
||||
Failures int `json:"failures"`
|
||||
// UpdatedAt 是最近一次状态变化的 UTC 时间。
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// TokenAcquiredAt 是最近一次获得平台会话令牌的时间。
|
||||
TokenAcquiredAt time.Time `json:"token_acquired_at,omitempty"`
|
||||
// TokenExpiresAt 是当前平台会话令牌的预计过期时间。
|
||||
TokenExpiresAt time.Time `json:"token_expires_at,omitempty"`
|
||||
// TokenRefreshAt 是最近一次或下一次令牌续期时间,具体语义由运行时实现保持兼容。
|
||||
TokenRefreshAt time.Time `json:"token_refresh_at,omitempty"`
|
||||
// TokenRemainingSeconds 是当前令牌剩余有效秒数。
|
||||
TokenRemainingSeconds int64 `json:"token_remaining_seconds,omitempty"`
|
||||
// TokenRefreshStatus 是令牌续期阶段的非敏感状态标签。
|
||||
TokenRefreshStatus string `json:"token_refresh_status,omitempty"`
|
||||
}
|
||||
|
||||
// RuntimePort 定义账号应用层需要的最小运行时控制能力;实现方不得把 HTTP 或 engine 类型泄漏给调用者。
|
||||
type RuntimePort interface {
|
||||
// UpdateCookie 把新 Cookie 同步到已存在的账号运行实例;缺少实例时应保持幂等无副作用。
|
||||
UpdateCookie(context.Context, string, string) error
|
||||
// RuntimeStatuses 返回当前已登记账号的状态快照;调用方可安全修改返回的 map。
|
||||
RuntimeStatuses(context.Context) (map[string]RuntimeStatus, error)
|
||||
// Restart 使用持久化凭证重启指定账号运行实例,并在完成后返回运行时错误。
|
||||
Restart(context.Context, string) error
|
||||
// RecoverExpiredCredential 在平台会话失效时触发账号凭证恢复;返回是否接受了恢复请求。
|
||||
RecoverExpiredCredential(context.Context, string) bool
|
||||
}
|
||||
|
||||
// CredentialWakePort 定义凭证恢复后唤醒自动化任务的最小能力,避免账号应用层依赖自动化实现包。
|
||||
type CredentialWakePort interface {
|
||||
// WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的任务。
|
||||
WakeCredentialBlocked(context.Context, string) error
|
||||
}
|
||||
|
||||
// RuntimeService 编排账号凭证写回后的运行时同步、重启和状态快照读取。
|
||||
type RuntimeService struct {
|
||||
// runtime 提供账号运行实例的生命周期与状态能力;可为空以兼容离线测试或未启用运行时的进程。
|
||||
runtime RuntimePort
|
||||
// wake 在凭证更新或重启完成后唤醒被凭证失效阻塞的自动化任务。
|
||||
wake CredentialWakePort
|
||||
}
|
||||
|
||||
// NewRuntimeService 构造账号运行时应用服务;运行时和唤醒端口都允许为空以保持无浏览器测试可运行。
|
||||
func NewRuntimeService(runtime RuntimePort, wake CredentialWakePort) *RuntimeService {
|
||||
return &RuntimeService{runtime: runtime, wake: wake}
|
||||
}
|
||||
|
||||
// UpdateCookie 同步运行时 Cookie 并唤醒凭证阻塞任务;外部端口错误向调用者保留但不泄漏敏感值。
|
||||
func (s *RuntimeService) UpdateCookie(ctx context.Context, accountID, value string) error {
|
||||
if s == nil {
|
||||
return errors.New("账号运行时服务未初始化")
|
||||
}
|
||||
// validationErr 保存 Cookie 同步输入校验错误。
|
||||
if validationErr := validateRuntimeInput(ctx, accountID); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
// wakeErr 保存自动化任务唤醒失败;该失败不阻断 Cookie 同步,避免凭证已更新但运行实例仍持有旧值。
|
||||
var wakeErr error
|
||||
if s.wake != nil {
|
||||
wakeErr = s.wake.WakeCredentialBlocked(ctx, accountID)
|
||||
}
|
||||
if s.runtime == nil {
|
||||
return wakeErr
|
||||
}
|
||||
// updateErr 保存运行实例 Cookie 同步错误;运行时错误优先于非阻断的唤醒错误返回。
|
||||
updateErr := s.runtime.UpdateCookie(ctx, accountID, value)
|
||||
if updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
return wakeErr
|
||||
}
|
||||
|
||||
// RuntimeStatuses 读取账号运行状态快照;未装配运行时返回空集合而不是伪造在线状态。
|
||||
func (s *RuntimeService) RuntimeStatuses(ctx context.Context) (map[string]RuntimeStatus, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("账号运行时服务未初始化")
|
||||
}
|
||||
// contextErr 保存状态快照读取前的取消错误。
|
||||
if contextErr := contextError(ctx); contextErr != nil {
|
||||
return nil, contextErr
|
||||
}
|
||||
if s.runtime == nil {
|
||||
return map[string]RuntimeStatus{}, nil
|
||||
}
|
||||
return s.runtime.RuntimeStatuses(ctx)
|
||||
}
|
||||
|
||||
// Restart 重启指定账号运行实例,并在成功后唤醒凭证阻塞任务。
|
||||
func (s *RuntimeService) Restart(ctx context.Context, accountID string) error {
|
||||
if s == nil {
|
||||
return errors.New("账号运行时服务未初始化")
|
||||
}
|
||||
// validationErr 保存账号运行时重启输入校验错误。
|
||||
if validationErr := validateRuntimeInput(ctx, accountID); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
if s.runtime != nil {
|
||||
// restartErr 保存运行实例重启错误;失败时不执行后续唤醒。
|
||||
if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil {
|
||||
return restartErr
|
||||
}
|
||||
}
|
||||
if s.wake != nil {
|
||||
// wakeErr 保存重启成功后的自动化任务唤醒结果。
|
||||
wakeErr := s.wake.WakeCredentialBlocked(ctx, accountID)
|
||||
return wakeErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 将平台会话失效恢复请求转发给运行时端口,不让 Server 直接持有 Manager 业务调用。
|
||||
func (s *RuntimeService) RecoverExpiredCredential(ctx context.Context, accountID string) bool {
|
||||
if s == nil || s.runtime == nil || validateRuntimeInput(ctx, accountID) != nil {
|
||||
return false
|
||||
}
|
||||
return s.runtime.RecoverExpiredCredential(ctx, accountID)
|
||||
}
|
||||
|
||||
// validateRuntimeInput 统一校验账号运行时调用的上下文和账号标识。
|
||||
func validateRuntimeInput(ctx context.Context, accountID string) error {
|
||||
// contextErr 保存账号标识校验前检查到的取消错误。
|
||||
if contextErr := contextError(ctx); contextErr != nil {
|
||||
return contextErr
|
||||
}
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return errors.New("账号标识不能为空")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// contextError 将 nil Context 视为可继续执行,并在已取消时阻止任何运行时副作用。
|
||||
func contextError(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// runtimePortFake 记录账号运行时端口调用并返回预置结果。
|
||||
type runtimePortFake struct {
|
||||
// updateErr 是 Cookie 同步操作的预置错误。
|
||||
updateErr error
|
||||
// restartErr 是账号重启操作的预置错误。
|
||||
restartErr error
|
||||
// statuses 是运行状态快照。
|
||||
statuses map[string]RuntimeStatus
|
||||
// updates 记录已同步的账号 Cookie。
|
||||
updates []string
|
||||
// restarts 记录已请求重启的账号。
|
||||
restarts []string
|
||||
}
|
||||
|
||||
// UpdateCookie 记录运行时 Cookie 同步请求。
|
||||
func (f *runtimePortFake) UpdateCookie(_ context.Context, accountID, value string) error {
|
||||
f.updates = append(f.updates, accountID+":"+value)
|
||||
return f.updateErr
|
||||
}
|
||||
|
||||
// RuntimeStatuses 返回预置状态快照。
|
||||
func (f *runtimePortFake) RuntimeStatuses(_ context.Context) (map[string]RuntimeStatus, error) {
|
||||
return f.statuses, nil
|
||||
}
|
||||
|
||||
// RecoverExpiredCredential 记录测试中的会话恢复请求并返回预设结果。
|
||||
func (f *runtimePortFake) RecoverExpiredCredential(context.Context, string) bool { return true }
|
||||
|
||||
// Restart 记录账号重启请求。
|
||||
func (f *runtimePortFake) Restart(_ context.Context, accountID string) error {
|
||||
f.restarts = append(f.restarts, accountID)
|
||||
return f.restartErr
|
||||
}
|
||||
|
||||
// wakePortFake 记录自动化任务唤醒请求。
|
||||
type wakePortFake struct {
|
||||
// err 是唤醒操作的预置错误。
|
||||
err error
|
||||
// accounts 记录已唤醒的账号。
|
||||
accounts []string
|
||||
}
|
||||
|
||||
// WakeCredentialBlocked 记录凭证阻塞任务唤醒请求。
|
||||
func (f *wakePortFake) WakeCredentialBlocked(_ context.Context, accountID string) error {
|
||||
f.accounts = append(f.accounts, accountID)
|
||||
return f.err
|
||||
}
|
||||
|
||||
// TestRuntimeServiceUpdateCookieSuccess 验证 Cookie 同步和任务唤醒的成功路径。
|
||||
func TestRuntimeServiceUpdateCookieSuccess(t *testing.T) {
|
||||
// runtime 保存运行时端口替身。
|
||||
runtime := &runtimePortFake{}
|
||||
// wake 保存自动化唤醒端口替身。
|
||||
wake := &wakePortFake{}
|
||||
// service 保存待测试的账号运行时应用服务。
|
||||
service := NewRuntimeService(runtime, wake)
|
||||
// updateErr 保存 Cookie 同步结果。
|
||||
if updateErr := service.UpdateCookie(context.Background(), "acc1", "cookie"); updateErr != nil {
|
||||
t.Fatalf("UpdateCookie returned error: %v", updateErr)
|
||||
}
|
||||
if len(runtime.updates) != 1 || runtime.updates[0] != "acc1:cookie" || len(wake.accounts) != 1 {
|
||||
t.Fatalf("unexpected side effects: runtime=%+v wake=%+v", runtime, wake)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeServiceUpdateCookieMissingRuntime 验证未装配运行时仍保持凭证写回幂等。
|
||||
func TestRuntimeServiceUpdateCookieMissingRuntime(t *testing.T) {
|
||||
// service 保存未装配运行时但已装配唤醒端口的应用服务。
|
||||
service := NewRuntimeService(nil, &wakePortFake{})
|
||||
// updateErr 保存未装配运行时的同步结果。
|
||||
if updateErr := service.UpdateCookie(context.Background(), "acc1", "cookie"); updateErr != nil {
|
||||
t.Fatalf("missing runtime should be idempotent: %v", updateErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeServiceCancellationAndErrors 验证取消、唤醒错误和运行时错误不会伪造成功。
|
||||
func TestRuntimeServiceCancellationAndErrors(t *testing.T) {
|
||||
// canceled 保存已取消的调用上下文。
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
// service 保存可执行错误路径的应用服务。
|
||||
service := NewRuntimeService(&runtimePortFake{updateErr: errors.New("runtime failed")}, &wakePortFake{})
|
||||
// canceledErr 保存取消上下文的同步错误。
|
||||
if canceledErr := service.UpdateCookie(canceled, "acc1", "cookie"); !errors.Is(canceledErr, context.Canceled) {
|
||||
t.Fatalf("canceled context error=%v", canceledErr)
|
||||
}
|
||||
// wakeErrService 保存唤醒失败的应用服务。
|
||||
wakeErrService := NewRuntimeService(&runtimePortFake{}, &wakePortFake{err: errors.New("wake failed")})
|
||||
// wakeErr 保存唤醒失败但 Cookie 同步仍完成后的返回错误。
|
||||
if wakeErr := wakeErrService.UpdateCookie(context.Background(), "acc1", "cookie"); wakeErr == nil || wakeErr.Error() != "wake failed" {
|
||||
t.Fatalf("wake error=%v", wakeErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeServiceRuntimeStatusesSnapshot 验证状态快照字段按应用 DTO 原样返回。
|
||||
func TestRuntimeServiceRuntimeStatusesSnapshot(t *testing.T) {
|
||||
// updatedAt 保存状态更新时间,确认时间字段不被 transport 层丢失。
|
||||
updatedAt := time.Now().UTC()
|
||||
// statuses 保存运行时端口提供的非敏感状态快照。
|
||||
statuses := map[string]RuntimeStatus{"acc1": {State: "online", Connected: true, UpdatedAt: updatedAt}}
|
||||
// service 保存状态读取应用服务。
|
||||
service := NewRuntimeService(&runtimePortFake{statuses: statuses}, nil)
|
||||
// got、statusErr 保存读取到的快照和错误。
|
||||
got, statusErr := service.RuntimeStatuses(context.Background())
|
||||
if statusErr != nil || got["acc1"].State != "online" || !got["acc1"].Connected || !got["acc1"].UpdatedAt.Equal(updatedAt) {
|
||||
t.Fatalf("snapshot=%+v err=%v", got, statusErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeServiceRecoversExpiredCredential 验证会话失效恢复由运行时端口接管并尊重取消上下文。
|
||||
func TestRuntimeServiceRecoversExpiredCredential(t *testing.T) {
|
||||
// service 保存绑定运行时端口的账号应用服务。
|
||||
service := NewRuntimeService(&runtimePortFake{}, nil)
|
||||
if !service.RecoverExpiredCredential(context.Background(), "acc1") {
|
||||
t.Fatal("expected runtime recovery to be accepted")
|
||||
}
|
||||
// canceled 保存已取消的请求上下文。
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if service.RecoverExpiredCredential(canceled, "acc1") {
|
||||
t.Fatal("canceled recovery must not reach runtime port")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user