推进P1登录管理器与通知不确定态收口
This commit is contained in:
1 parent
417723d2c0
commit
0a756c408e
17 files changed
+589
-31
No files matched your search
@@ -794,6 +794,9 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | P1 商品批量发布应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `items.BatchRunner`、批次/明细模型、租约/取消/中断/收口 Port 和测试;批量 worker 的逐行 claim、失败分类、租约续期和上传清理从 Server 迁入应用层,Server 仅保留既有批量平台单行适配与数据库转换,未扩大新的临时低层白名单;批量 HTTP/应用回归、架构门禁和中文注释门禁通过。单行平台适配、商品同步及其他领域 Port 仍待治理 |
|
||||
| 2026-08-15 | P1 Engine 内部任务生命周期切片 | 已完成本切片 | Engine 迟到 API 续期 watcher 纳入账号生命周期 `beginTask/finishTask`,继承账号运行 Context,StopContext 会等待其退出;WS recorder 关闭等待改为 Context-aware,未启动 recorder 不误报超时,停止超时后可重试;新增任务超时/重试和迟到 watcher 回归,Engine 全量测试、聚焦 race 和中文注释门禁通过。其他 Engine 网络/浏览器任务仍需统一清单审计 |
|
||||
| 2026-08-15 | P1 账号自动化动作错误收口切片 | 已完成本切片 | 自动评价/擦亮任务不再吞 Cookie、FinishRun、MarkRateScan/MarkPolished 错误;外部动作成功但本地状态失败会写 `needs_review` 并返回 `errAutomationNeedsReview`,隔离写入失败使用 `errors.Join` 保留双重原因;新增单失败、双失败和日期写入失败回归,automation 全量测试通过。账号任务其他动作和通知旁路仍待盘点 |
|
||||
| 2026-08-15 | P1 手动登录凭证应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `account.LoginService`,输入 DTO 不含 Cookie/密码;明文 Cookie 只由 Server request-scoped `CookieWriter` 在凭证锁内完成归属校验、写入和旧 Token 清理,登录后审计/资料刷新/运行时重启通过生命周期 Port;新增成功、归属失败、写入失败和缺失依赖测试,Server/应用回归及中文注释门禁通过。密码登录、扫码登录和更新凭证流程仍待统一协调 |
|
||||
| 2026-08-15 | P1 账号管理器全局 Stop fencing 切片 | 已完成本切片 | `Manager.StopAllContext` 在收集账号前建立全局 stopping fence,停止期间拒绝新的 Start;单账号 Stop 超时保留 stopping 标记,防止存活实例被重启替换;全量停止完成后解除 fence,补充并发启动/停止和已取消 Context 兼容回归,account/Server 测试及 race 通过。删除任务状态查询和统一生命周期清单仍待完善 |
|
||||
| 2026-08-15 | P1 通知 outbox 不确定状态隔离切片 | 已完成本切片 | 新增 SQLite/MySQL/Postgres `notification_outbox.uncertain_at` 迁移及 `MarkOutboxUncertain`;通知已发送但 `CompleteOutbox` 失败时原子转 `uncertain`、清除租约并禁止自动重发,隔离失败用 `errors.Join` 记录;无效渠道清理不再吞错;新增 SQLite、通知 worker 和三库矩阵回归,notify/db race、全量门禁通过。人工核对查询与运维展示仍待补充 |
|
||||
|
||||
### 11.2 执行纠偏审计(2026-08-15)
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ type Manager struct {
|
||||
accounts map[string]*managedAccount
|
||||
// stopping 保存正在执行删除/停止 fencing 的账号,阻止其被并发重新启动。
|
||||
stopping map[string]struct{}
|
||||
runCtx context.Context
|
||||
// stoppingAll 表示管理器正在执行全量关闭;关闭期间禁止新账号进入运行实例表。
|
||||
stoppingAll bool
|
||||
runCtx context.Context
|
||||
}
|
||||
|
||||
// managedAccount 保存managed账号,供当前处理流程使用
|
||||
@@ -36,6 +38,8 @@ type managedAccount struct {
|
||||
acc *engine.Account
|
||||
cancel context.CancelFunc
|
||||
done chan struct{} // Run 返回后关闭
|
||||
// stopping 表示该运行实例已经收到停止请求;保持为 true 直到完整收束,防止重启逃逸。
|
||||
stopping bool
|
||||
err error
|
||||
}
|
||||
|
||||
@@ -57,6 +61,9 @@ func NewManager(store *db.Store, handler engine.Handler, logger *slog.Logger) *M
|
||||
// 已禁用的账号不启动;启动失败的账号记录错误但不影响其他账号。
|
||||
// StartAll 启动All。
|
||||
func (m *Manager) StartAll(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.runCtx = ctx
|
||||
m.mu.Unlock()
|
||||
@@ -83,7 +90,14 @@ StartAll 只把启用账号交给运行时 supervisor。
|
||||
|
||||
// Start 启动单个账号(若已在运行则跳过;若上次实例已退出则清理后重启)。
|
||||
func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.stoppingAll {
|
||||
m.mu.Unlock()
|
||||
return fmt.Errorf("账号管理器正在停止")
|
||||
}
|
||||
// stopping 表示当前账号是否已进入删除/停止 fencing。
|
||||
if _, stopping := m.stopping[cookieID]; stopping {
|
||||
m.mu.Unlock()
|
||||
@@ -94,6 +108,10 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
|
||||
}
|
||||
if // ma、ok 保存ma、ok,供当前处理流程使用
|
||||
ma, ok := m.accounts[cookieID]; ok {
|
||||
if ma.stopping {
|
||||
m.mu.Unlock()
|
||||
return fmt.Errorf("账号 %s 正在停止", cookieID)
|
||||
}
|
||||
// 已存在:若已退出则清理后重启,否则跳过。select 非阻塞,持锁安全。
|
||||
select {
|
||||
case <-ma.done:
|
||||
@@ -169,6 +187,10 @@ func (m *Manager) StopContext(ctx context.Context, cookieID string) error {
|
||||
m.mu.Lock()
|
||||
// ma、ok 保存ma、ok,供当前处理流程使用
|
||||
ma, ok := m.accounts[cookieID]
|
||||
if ok {
|
||||
// stopping 标记会阻止 Start 在停止上下文超时后重新替换仍可能存活的运行实例。
|
||||
ma.stopping = true
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return nil
|
||||
@@ -274,6 +296,8 @@ func (m *Manager) StopAllContext(ctx context.Context) error {
|
||||
ctx = context.Background()
|
||||
}
|
||||
m.mu.Lock()
|
||||
// stoppingAll 在收集账号前建立全局 fencing,防止并发 Start 把新实例遗漏在本次关闭之外。
|
||||
m.stoppingAll = true
|
||||
// ids 保存ids,供当前处理流程使用
|
||||
ids := make([]string, 0, len(m.accounts))
|
||||
// id 表示当前遍历过程中的标识
|
||||
@@ -288,5 +312,11 @@ func (m *Manager) StopAllContext(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
m.mu.Lock()
|
||||
// stoppingAll 仅在所有已登记实例收束后解除;超时返回时保留 fencing,供下一次 StopAllContext 重试。
|
||||
if len(m.accounts) == 0 {
|
||||
m.stoppingAll = false
|
||||
}
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -116,6 +117,25 @@ func TestManagerStoppingFence(t *testing.T) {
|
||||
mgr.EndStopping("fenced")
|
||||
}
|
||||
|
||||
// TestManagerGlobalStoppingFence 验证全量关闭期间不允许新的账号运行实例进入管理器。
|
||||
func TestManagerGlobalStoppingFence(t *testing.T) {
|
||||
// mgr 是只验证生命周期 fencing 的管理器,不需要数据库或平台处理器。
|
||||
mgr := NewManager(nil, noopHandler{}, nil)
|
||||
mgr.mu.Lock()
|
||||
// stoppingAll 模拟 StopAllContext 已经建立的全局关闭屏障。
|
||||
mgr.stoppingAll = true
|
||||
mgr.mu.Unlock()
|
||||
|
||||
// err 表示全局关闭期间尝试启动账号得到的拒绝原因。
|
||||
err := mgr.Start(context.Background(), "during-stop", "cookie")
|
||||
if err == nil {
|
||||
t.Fatal("全量停止期间不应允许启动账号")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "正在停止") {
|
||||
t.Fatalf("全量停止错误=%v,未说明停止 fencing", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestManagerConcurrentStartCreatesSingleManagedInstance 负责TestManagerConcurrent开始CreatesSingleManagedInstance相关处理。
|
||||
func TestManagerConcurrentStartCreatesSingleManagedInstance(t *testing.T) {
|
||||
// dbPath 保存db路径,供当前处理流程使用
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CreateCookieInput 是手动录入账号 Cookie 用例的非敏感输入;明文 Cookie 由调用方专用端口封装。
|
||||
type CreateCookieInput struct {
|
||||
// AccountID 是待创建的平台账号稳定标识。
|
||||
AccountID string
|
||||
// UserID 是当前用户的本地身份标识。
|
||||
UserID int64
|
||||
// LoginMethod 是触发本次登录的方式;空值按手动 Cookie 录入处理。
|
||||
LoginMethod string
|
||||
}
|
||||
|
||||
// CookieWriter 定义一次性写入账号凭证的端口;实现方负责在最小作用域内持有明文 Cookie。
|
||||
type CookieWriter interface {
|
||||
// CreateOwnedCookie 原子校验账号归属并写入凭证;明文不应进入应用层 DTO 或日志。
|
||||
CreateOwnedCookie(context.Context, string, int64) error
|
||||
}
|
||||
|
||||
// LoginLifecyclePort 定义凭证成功写入后的审计、启用、资料刷新和运行时同步边界。
|
||||
type LoginLifecyclePort interface {
|
||||
// AfterSuccessfulLogin 在凭证写入并释放凭证锁后完成后续登录编排。
|
||||
AfterSuccessfulLogin(context.Context, int64, string, string)
|
||||
}
|
||||
|
||||
// LoginService 编排手动 Cookie 登录用例,不保存任何敏感凭证状态。
|
||||
type LoginService struct {
|
||||
// lifecycle 负责凭证写入后的审计、资料和运行时适配。
|
||||
lifecycle LoginLifecyclePort
|
||||
}
|
||||
|
||||
// NewLoginService 构造账号登录应用服务并校验必需的生命周期端口。
|
||||
func NewLoginService(lifecycle LoginLifecyclePort) (*LoginService, error) {
|
||||
if lifecycle == nil {
|
||||
return nil, errors.New("账号登录生命周期端口未初始化")
|
||||
}
|
||||
return &LoginService{lifecycle: lifecycle}, nil
|
||||
}
|
||||
|
||||
// CreateCookie 执行一次手动 Cookie 登录;凭证仅通过调用方提供的专用写入端口传递。
|
||||
func (s *LoginService) CreateCookie(ctx context.Context, input CreateCookieInput, writer CookieWriter) error {
|
||||
if s == nil || s.lifecycle == nil {
|
||||
return errors.New("账号登录服务未初始化")
|
||||
}
|
||||
if writer == nil {
|
||||
return errors.New("账号 Cookie 写入端口未初始化")
|
||||
}
|
||||
if strings.TrimSpace(input.AccountID) == "" {
|
||||
return errors.New("缺少账号 ID")
|
||||
}
|
||||
// writeErr 保存基础设施端口写入凭证时返回的错误。
|
||||
writeErr := writer.CreateOwnedCookie(ctx, input.AccountID, input.UserID)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// method 是归一化后的登录方式,供审计和运行时适配器保持统一语义。
|
||||
method := normalizeLoginMethod(input.LoginMethod)
|
||||
s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method)
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeLoginMethod 将兼容的登录方式别名归一化为审计使用的稳定值。
|
||||
func normalizeLoginMethod(method string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(method)) {
|
||||
case "", "manual", "cookie", "manual_cookie":
|
||||
return "manual"
|
||||
case "password", "password_login":
|
||||
return "password"
|
||||
case "qr", "qr_login", "qr_scan":
|
||||
return "qr_scan"
|
||||
default:
|
||||
return strings.ToLower(strings.TrimSpace(method))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeCookieWriter 是登录应用服务测试用的凭证写入端口替身。
|
||||
type fakeCookieWriter struct {
|
||||
// err 是写入凭证时需要模拟的失败。
|
||||
err error
|
||||
// accountID 和 userID 保存最近一次写入请求,验证敏感值未进入应用输入。
|
||||
accountID string
|
||||
userID int64
|
||||
called bool
|
||||
}
|
||||
|
||||
// CreateOwnedCookie 记录写入请求但不接收明文 Cookie。
|
||||
func (w *fakeCookieWriter) CreateOwnedCookie(_ context.Context, accountID string, userID int64) error {
|
||||
w.called = true
|
||||
w.accountID = accountID
|
||||
w.userID = userID
|
||||
return w.err
|
||||
}
|
||||
|
||||
// fakeLoginLifecycle 是登录后续编排测试用的生命周期端口替身。
|
||||
type fakeLoginLifecycle struct {
|
||||
// calls 保存登录后续编排的调用次数。
|
||||
calls int
|
||||
// userID、accountID 和 method 保存最近一次登录后续输入。
|
||||
userID int64
|
||||
accountID string
|
||||
method string
|
||||
}
|
||||
|
||||
// AfterSuccessfulLogin 记录登录成功后的编排输入。
|
||||
func (l *fakeLoginLifecycle) AfterSuccessfulLogin(_ context.Context, userID int64, accountID, method string) {
|
||||
l.calls++
|
||||
l.userID = userID
|
||||
l.accountID = accountID
|
||||
l.method = method
|
||||
}
|
||||
|
||||
// TestLoginServiceRequiresLifecycleAndWriter 验证必需端口缺失时快速失败。
|
||||
func TestLoginServiceRequiresLifecycleAndWriter(t *testing.T) {
|
||||
// lifecycle 是有效的生命周期端口替身。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// missingLifecycleErr 保存缺少生命周期端口时的构造错误。
|
||||
_, missingLifecycleErr := NewLoginService(nil)
|
||||
if missingLifecycleErr == nil {
|
||||
t.Fatal("缺少生命周期端口时应构造失败")
|
||||
}
|
||||
// service 保存使用有效生命周期端口构造的登录服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// missingWriterErr 保存缺少凭证写入端口时的执行错误。
|
||||
missingWriterErr := service.CreateCookie(context.Background(), CreateCookieInput{AccountID: "acc1"}, nil)
|
||||
if missingWriterErr == nil {
|
||||
t.Fatal("缺少 Cookie 写入端口时应失败")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceCreateCookieKeepsCredentialOutOfInput 验证成功登录只通过凭证端口写入并触发后续编排。
|
||||
func TestLoginServiceCreateCookieKeepsCredentialOutOfInput(t *testing.T) {
|
||||
// lifecycle 是记录后续审计和运行时编排的测试替身。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// writer 是不暴露 Cookie 参数的凭证写入测试替身。
|
||||
writer := &fakeCookieWriter{}
|
||||
// service 保存使用有效生命周期端口构造的登录服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// createErr 保存成功用例执行时的错误。
|
||||
createErr := service.CreateCookie(context.Background(), CreateCookieInput{AccountID: "acc1", UserID: 7, LoginMethod: "cookie"}, writer)
|
||||
if createErr != nil {
|
||||
t.Fatalf("创建 Cookie 登录失败: %v", createErr)
|
||||
}
|
||||
if !writer.called || writer.accountID != "acc1" || writer.userID != 7 {
|
||||
t.Fatalf("凭证写入端口输入异常: %+v", writer)
|
||||
}
|
||||
if lifecycle.calls != 1 || lifecycle.accountID != "acc1" || lifecycle.userID != 7 || lifecycle.method != "manual" {
|
||||
t.Fatalf("登录后续编排输入异常: %+v", lifecycle)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceCreateCookieStopsAfterWriterFailure 验证凭证写入失败时不会执行成功后续编排。
|
||||
func TestLoginServiceCreateCookieStopsAfterWriterFailure(t *testing.T) {
|
||||
// expectedErr 是凭证写入端口需要返回的故障。
|
||||
expectedErr := errors.New("凭证写入失败")
|
||||
// lifecycle 是用于确认未被调用的后续编排替身。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// writer 是返回预期错误的凭证写入替身。
|
||||
writer := &fakeCookieWriter{err: expectedErr}
|
||||
// service 保存使用有效生命周期端口构造的登录服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// callErr 保存凭证写入失败后由应用服务传出的错误。
|
||||
callErr := service.CreateCookie(context.Background(), CreateCookieInput{AccountID: "acc1"}, writer)
|
||||
if !errors.Is(callErr, expectedErr) {
|
||||
t.Fatalf("应保留凭证写入错误,got %v", callErr)
|
||||
}
|
||||
if lifecycle.calls != 0 {
|
||||
t.Fatal("凭证写入失败时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceCreateCookiePropagatesOwnershipFailure 验证凭证端口拒绝跨用户账号时不会伪造登录成功。
|
||||
func TestLoginServiceCreateCookiePropagatesOwnershipFailure(t *testing.T) {
|
||||
// ownershipErr 是持久化端口完成账号归属校验后返回的越权错误。
|
||||
ownershipErr := errors.New("账号不属于当前用户")
|
||||
// lifecycle 是用于确认越权请求未进入成功后续编排的测试替身。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// writer 是模拟归属校验失败的凭证写入端口。
|
||||
writer := &fakeCookieWriter{err: ownershipErr}
|
||||
// service 保存使用有效生命周期端口构造的登录服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// callErr 保存归属校验失败后由应用服务传出的错误。
|
||||
callErr := service.CreateCookie(context.Background(), CreateCookieInput{AccountID: "other", UserID: 7}, writer)
|
||||
if !errors.Is(callErr, ownershipErr) {
|
||||
t.Fatalf("应保留归属校验错误,got %v", callErr)
|
||||
}
|
||||
if lifecycle.calls != 0 {
|
||||
t.Fatal("归属校验失败时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
{"chat_messages", "message_key"},
|
||||
{"notification_outbox", "uncertain_at"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -1170,8 +1170,27 @@ func TestMultiDB_Notifications(t *testing.T) {
|
||||
if err != nil || len(messages) != 1 {
|
||||
t.Fatalf("ClaimOutbox: messages=%+v err=%v", messages, err)
|
||||
}
|
||||
// uncertain、err 保存三方言不确定隔离结果和数据库错误。
|
||||
uncertain, err := s.Notifications.MarkOutboxUncertain(ctx, messages[0].ID, "worker", "确认落库失败")
|
||||
if err != nil || !uncertain {
|
||||
t.Fatalf("MarkOutboxUncertain: uncertain=%v err=%v", uncertain, err)
|
||||
}
|
||||
// afterUncertain、err 保存不确定消息再次领取的结果和数据库错误。
|
||||
afterUncertain, err := s.Notifications.ClaimOutbox(ctx, "worker-2", time.Now().Add(time.Minute), 10)
|
||||
if err != nil || len(afterUncertain) != 0 {
|
||||
t.Fatalf("uncertain outbox was claimable: messages=%+v err=%v", afterUncertain, err)
|
||||
}
|
||||
// enqueueErr 保存第二条消息重新入队时的数据库错误。
|
||||
if enqueueErr := s.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{{ChannelID: chID, EventType: "test-complete", Body: "body"}}); enqueueErr != nil {
|
||||
t.Fatalf("EnqueueOutbox complete: %v", enqueueErr)
|
||||
}
|
||||
// completeMessages、err 保存第二条消息领取结果和数据库错误。
|
||||
completeMessages, err := s.Notifications.ClaimOutbox(ctx, "worker-3", time.Now(), 10)
|
||||
if err != nil || len(completeMessages) != 1 {
|
||||
t.Fatalf("ClaimOutbox complete: messages=%+v err=%v", completeMessages, err)
|
||||
}
|
||||
if // completed、err 保存completed、err,供当前处理流程使用
|
||||
completed, err := s.Notifications.CompleteOutbox(ctx, messages[0].ID, "worker"); err != nil || !completed {
|
||||
completed, err := s.Notifications.CompleteOutbox(ctx, completeMessages[0].ID, "worker-3"); err != nil || !completed {
|
||||
t.Fatalf("CompleteOutbox: completed=%v err=%v", completed, err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -62,6 +62,11 @@ func TestNotificationOutboxLeaseFencesStaleWorker(t *testing.T) {
|
||||
completed, err := store.Notifications.CompleteOutbox(ctx, first[0].ID, "worker-1"); err != nil || completed {
|
||||
t.Fatalf("stale completion: completed=%v err=%v", completed, err)
|
||||
}
|
||||
// staleUncertain、err 保存旧 worker 尝试隔离当前消息的结果和数据库错误。
|
||||
staleUncertain, err := store.Notifications.MarkOutboxUncertain(ctx, first[0].ID, "worker-1", "旧 worker 确认失败")
|
||||
if err != nil || staleUncertain {
|
||||
t.Fatalf("stale uncertain: uncertain=%v err=%v", staleUncertain, err)
|
||||
}
|
||||
if // retried、err 保存retried、err,供当前处理流程使用
|
||||
retried, err := store.Notifications.RetryOutbox(ctx, second[0].ID, "worker-2", "temporary", now.Add(2*time.Minute).Unix(), false); err != nil || !retried {
|
||||
t.Fatalf("retry: retried=%v err=%v", retried, err)
|
||||
@@ -75,8 +80,79 @@ func TestNotificationOutboxLeaseFencesStaleWorker(t *testing.T) {
|
||||
if err != nil || len(due) != 1 {
|
||||
t.Fatalf("due retry claim: messages=%+v err=%v", due, err)
|
||||
}
|
||||
if // completed、err 保存completed、err,供当前处理流程使用
|
||||
completed, err := store.Notifications.CompleteOutbox(ctx, due[0].ID, "worker-3"); err != nil || !completed {
|
||||
t.Fatalf("complete: completed=%v err=%v", completed, err)
|
||||
// uncertain、err 保存不确定状态隔离结果和数据库错误。
|
||||
uncertain, err := store.Notifications.MarkOutboxUncertain(ctx, due[0].ID, "worker-3", "本地确认失败")
|
||||
if err != nil || !uncertain {
|
||||
t.Fatalf("mark uncertain: uncertain=%v err=%v", uncertain, err)
|
||||
}
|
||||
// status、workerToken、lastError、uncertainAt 保存隔离后的状态、租约和诊断信息。
|
||||
var uncertainStatus, uncertainWorkerToken, uncertainLastError string
|
||||
// uncertainAt 保存消息进入不确定隔离态的 Unix 时间戳。
|
||||
var uncertainAt int64
|
||||
// queryErr 保存读取不确定状态时的数据库错误。
|
||||
if queryErr := store.DB.QueryRowContext(ctx, `SELECT status,worker_token,last_error,uncertain_at
|
||||
FROM notification_outbox WHERE id=?`, due[0].ID).
|
||||
Scan(&uncertainStatus, &uncertainWorkerToken, &uncertainLastError, &uncertainAt); queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if uncertainStatus != "uncertain" || uncertainWorkerToken != "" || uncertainLastError != "本地确认失败" || uncertainAt == 0 {
|
||||
t.Fatalf("unexpected uncertain state: status=%q worker=%q error=%q at=%d", uncertainStatus, uncertainWorkerToken, uncertainLastError, uncertainAt)
|
||||
}
|
||||
// afterUncertain、err 保存隔离消息再次领取的结果,确保不会自动重发。
|
||||
afterUncertain, err := store.Notifications.ClaimOutbox(ctx, "worker-4", now.Add(4*time.Minute), 10)
|
||||
if err != nil || len(afterUncertain) != 0 {
|
||||
t.Fatalf("uncertain message was claimable: messages=%+v err=%v", afterUncertain, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationOutboxPermanentRetry 将达到重试上限的发送失败消息标记为 dead 隔离。
|
||||
func TestNotificationOutboxPermanentRetry(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库及其关闭责任。
|
||||
store, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
// ctx 保存本测试使用的根上下文。
|
||||
ctx := context.Background()
|
||||
// ok、err 保存测试用户创建结果和数据库错误。
|
||||
ok, err := store.Users.Create(ctx, "notify-dead", "notify-dead@example.com", "pw")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("create owner: ok=%v err=%v", ok, err)
|
||||
}
|
||||
// owner、ownerErr 保存通知渠道所属用户和查询错误。
|
||||
owner, ownerErr := store.Users.GetByUsername(ctx, "notify-dead")
|
||||
if ownerErr != nil {
|
||||
t.Fatal(ownerErr)
|
||||
}
|
||||
// result、err 保存通知渠道插入结果和数据库错误。
|
||||
result, err := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,?,?)`, "dead", "webhook", `{}`, 1, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// channelID、err 保存渠道标识和读取标识时的错误。
|
||||
channelID, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// enqueueErr 保存写入待发送消息时的数据库错误。
|
||||
if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{{ChannelID: channelID, EventType: "test", Body: "body"}}); enqueueErr != nil {
|
||||
t.Fatal(enqueueErr)
|
||||
}
|
||||
// claimed、err 保存领取到的消息和数据库错误。
|
||||
claimed, err := store.Notifications.ClaimOutbox(ctx, "worker-dead", time.Unix(100, 0), 10)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim: messages=%+v err=%v", claimed, err)
|
||||
}
|
||||
// updated、err 保存永久失败状态更新结果和数据库错误。
|
||||
updated, err := store.Notifications.RetryOutbox(ctx, claimed[0].ID, "worker-dead", "远端发送失败", time.Unix(200, 0).Unix(), true)
|
||||
if err != nil || !updated {
|
||||
t.Fatalf("retry dead: updated=%v err=%v", updated, err)
|
||||
}
|
||||
// status 保存永久失败消息的最终隔离状态。
|
||||
var status string
|
||||
// queryErr 保存读取永久失败状态时的数据库错误。
|
||||
if queryErr := store.DB.QueryRowContext(ctx, `SELECT status FROM notification_outbox WHERE id=?`, claimed[0].ID).Scan(&status); queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "dead" {
|
||||
t.Fatalf("status=%q want dead", status)
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,23 @@ func (n *Notifications) CompleteOutbox(ctx context.Context, id int64, workerToke
|
||||
return err == nil && count == 1, err
|
||||
}
|
||||
|
||||
// MarkOutboxUncertain 将外部发送成功但本地确认失败的消息隔离,阻止租约过期后自动重复发送。
|
||||
// 只有仍持有当前租约的 worker 才能完成状态转移;返回 false 表示租约已被其他 worker 接管。
|
||||
func (n *Notifications) MarkOutboxUncertain(ctx context.Context, id int64, workerToken, message string) (bool, error) {
|
||||
// uncertainAt 保存消息进入不确定隔离态的 Unix 时间戳,便于运维定位确认失败窗口。
|
||||
uncertainAt := time.Now().Unix()
|
||||
// result、err 保存状态更新结果和数据库错误。
|
||||
result, err := n.DB.ExecContext(ctx, `UPDATE notification_outbox
|
||||
SET status='uncertain',uncertain_at=?,next_attempt_at=0,lease_expires_at=0,worker_token='',last_error=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=?`, uncertainAt, message, id, workerToken)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// affected、err 保存本次状态更新影响的行数和读取错误。
|
||||
affected, err := result.RowsAffected()
|
||||
return err == nil && affected == 1, err
|
||||
}
|
||||
|
||||
// RetryOutbox 重试Outbox。
|
||||
func (n *Notifications) RetryOutbox(ctx context.Context, id int64, workerToken, message string, nextAttemptAt int64, permanent bool) (bool, error) {
|
||||
// status 保存状态,供当前处理流程使用
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -259,7 +260,13 @@ func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
if channel == nil {
|
||||
_, _ = n.repository.CompleteOutbox(ctx, message.ID, workerToken)
|
||||
// completed、completeErr 保存无效渠道消息的清理结果和数据库错误。
|
||||
completed, completeErr := n.repository.CompleteOutbox(ctx, message.ID, workerToken)
|
||||
if completeErr != nil {
|
||||
n.logger.Warn("清理无效通知渠道消息失败", "outbox_id", message.ID, "err", logsafe.Error(completeErr))
|
||||
} else if !completed {
|
||||
n.logger.Warn("清理无效通知渠道消息时租约已转移", "outbox_id", message.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if // sendErr 保存sendErr,供当前处理流程使用
|
||||
@@ -270,7 +277,15 @@ func (n *Notifier) drainOutbox(ctx context.Context) {
|
||||
}
|
||||
if // completed、completeErr 保存completed、completeErr,供当前处理流程使用
|
||||
completed, completeErr := n.repository.CompleteOutbox(ctx, message.ID, workerToken); completeErr != nil {
|
||||
n.logger.Warn("确认通知投递完成失败", "outbox_id", message.ID, "err", completeErr)
|
||||
// uncertain、uncertainErr 保存发送成功后的隔离结果和隔离失败错误。
|
||||
uncertain, uncertainErr := n.repository.MarkOutboxUncertain(ctx, message.ID, workerToken, completeErr.Error())
|
||||
if uncertainErr != nil {
|
||||
n.logger.Error("确认通知投递完成失败且无法隔离消息", "outbox_id", message.ID, "err", logsafe.Error(errors.Join(completeErr, uncertainErr)))
|
||||
} else if !uncertain {
|
||||
n.logger.Warn("确认通知投递完成失败且租约已转移", "outbox_id", message.ID, "err", logsafe.Error(completeErr))
|
||||
} else {
|
||||
n.logger.Warn("通知已发送但本地确认失败,消息已隔离", "outbox_id", message.ID, "err", logsafe.Error(completeErr))
|
||||
}
|
||||
} else if !completed {
|
||||
n.logger.Warn("通知 outbox 租约已转移", "outbox_id", message.ID)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -15,6 +16,69 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// scriptedOutboxRepository 为 outbox worker 测试提供可控的领取、确认和隔离结果。
|
||||
type scriptedOutboxRepository struct {
|
||||
// channel 保存 worker 发送时返回的渠道配置。
|
||||
channel *db.NotificationChannel
|
||||
// pending 保存下一次 ClaimOutbox 应返回的消息;领取后立即清空以模拟持久化状态转移。
|
||||
pending []db.NotificationOutboxMessage
|
||||
// completeErr 保存本地完成确认故障,用于验证外部成功后的不确定隔离。
|
||||
completeErr error
|
||||
// uncertainResult 保存隔离调用是否成功。
|
||||
uncertainResult bool
|
||||
// uncertainErr 保存隔离状态写入故障。
|
||||
uncertainErr error
|
||||
// uncertainCalls 记录隔离调用次数。
|
||||
uncertainCalls int
|
||||
// retryCalls 记录发送失败重试调用次数。
|
||||
retryCalls int
|
||||
}
|
||||
|
||||
// AccountChannels 返回测试不使用的账号渠道列表。
|
||||
func (r *scriptedOutboxRepository) AccountChannels(context.Context, string) ([]db.NotificationChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// EnqueueOutbox 返回测试不使用的入队结果。
|
||||
func (r *scriptedOutboxRepository) EnqueueOutbox(context.Context, []db.NotificationOutboxInput) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimOutbox 返回一次可控的 outbox 消息并模拟领取后不再重复领取。
|
||||
func (r *scriptedOutboxRepository) ClaimOutbox(context.Context, string, time.Time, int) ([]db.NotificationOutboxMessage, error) {
|
||||
// messages 保存本次领取的消息,并在返回前清空替身队列以模拟一次性领取。
|
||||
messages := r.pending
|
||||
r.pending = nil
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// GetChannel 返回 worker 发送所需的测试渠道。
|
||||
func (r *scriptedOutboxRepository) GetChannel(context.Context, int64) (*db.NotificationChannel, error) {
|
||||
return r.channel, nil
|
||||
}
|
||||
|
||||
// CompleteOutbox 返回预置的本地确认故障,模拟发送成功后的落库失败。
|
||||
func (r *scriptedOutboxRepository) CompleteOutbox(context.Context, int64, string) (bool, error) {
|
||||
return false, r.completeErr
|
||||
}
|
||||
|
||||
// MarkOutboxUncertain 记录不确定隔离调用并返回预置结果。
|
||||
func (r *scriptedOutboxRepository) MarkOutboxUncertain(context.Context, int64, string, string) (bool, error) {
|
||||
r.uncertainCalls++
|
||||
return r.uncertainResult, r.uncertainErr
|
||||
}
|
||||
|
||||
// RetryOutbox 记录发送失败重试调用,便于断言发送成功不会进入重试。
|
||||
func (r *scriptedOutboxRepository) RetryOutbox(context.Context, int64, string, string, int64, bool) (bool, error) {
|
||||
r.retryCalls++
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// GetSetting 返回测试不使用的系统设置值。
|
||||
func (r *scriptedOutboxRepository) GetSetting(context.Context, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// nilLogger 返回一个丢弃所有输出的 logger,用于不需要日志噪声的测试。
|
||||
func nilLogger() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
@@ -148,6 +212,40 @@ func TestNotifyEventUsesPersistentOutboxWhenStarted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDrainOutbox_SendSuccessCompletionFailureQuarantines 验证外部发送成功但本地确认失败时进入不确定隔离且不重发。
|
||||
func TestDrainOutbox_SendSuccessCompletionFailureQuarantines(t *testing.T) {
|
||||
// calls 保存测试 HTTP 服务实际收到的请求次数。
|
||||
var calls int32
|
||||
// server 保存接收测试通知的本地 HTTP 服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&calls, 1)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
// repository 保存可控的 outbox 状态转换替身。
|
||||
repository := &scriptedOutboxRepository{
|
||||
channel: &db.NotificationChannel{ID: 7, Type: "webhook", Config: `{"webhook_url":"` + server.URL + `"}`},
|
||||
pending: []db.NotificationOutboxMessage{{ID: 11, ChannelID: 7, EventType: EventSystemError, Body: "正文", AttemptCount: 1}},
|
||||
completeErr: errors.New("确认落库失败"),
|
||||
uncertainResult: true,
|
||||
}
|
||||
// notifier 保存使用替身 repository 的通知器。
|
||||
notifier := NewWithRepository("cid", repository, nilLogger())
|
||||
notifier.started.Store(true)
|
||||
notifier.drainOutbox(context.Background())
|
||||
notifier.drainOutbox(context.Background())
|
||||
if // got 保存外部服务收到的请求次数。
|
||||
got := atomic.LoadInt32(&calls); got != 1 {
|
||||
t.Fatalf("send count=%d want 1", got)
|
||||
}
|
||||
if repository.uncertainCalls != 1 {
|
||||
t.Fatalf("uncertain calls=%d want 1", repository.uncertainCalls)
|
||||
}
|
||||
if repository.retryCalls != 0 {
|
||||
t.Fatalf("retry calls=%d want 0", repository.retryCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotifyAccountAlert_LevelLabels 覆盖 levelLabel 各分支。
|
||||
func TestNotifyAccountAlert_LevelLabels(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
|
||||
@@ -20,6 +20,8 @@ type Repository interface {
|
||||
GetChannel(ctx context.Context, channelID int64) (*db.NotificationChannel, error)
|
||||
// CompleteOutbox 确认当前 worker 已完成 outbox 消息。
|
||||
CompleteOutbox(ctx context.Context, messageID int64, workerToken string) (bool, error)
|
||||
// MarkOutboxUncertain 隔离外部发送成功但本地确认失败的 outbox 消息。
|
||||
MarkOutboxUncertain(ctx context.Context, messageID int64, workerToken, lastError string) (bool, error)
|
||||
// RetryOutbox 写入 outbox 消息的重试状态。
|
||||
RetryOutbox(ctx context.Context, messageID int64, workerToken, lastError string, nextAttemptAt int64, permanent bool) (bool, error)
|
||||
// GetSetting 读取系统设置中的字符串值。
|
||||
@@ -59,6 +61,11 @@ func (r storeRepository) CompleteOutbox(ctx context.Context, messageID int64, wo
|
||||
return r.store.Notifications.CompleteOutbox(ctx, messageID, workerToken)
|
||||
}
|
||||
|
||||
// MarkOutboxUncertain 委托通知 outbox 不确定状态隔离。
|
||||
func (r storeRepository) MarkOutboxUncertain(ctx context.Context, messageID int64, workerToken, lastError string) (bool, error) {
|
||||
return r.store.Notifications.MarkOutboxUncertain(ctx, messageID, workerToken, lastError)
|
||||
}
|
||||
|
||||
// RetryOutbox 委托通知 outbox 重试状态更新。
|
||||
func (r storeRepository) RetryOutbox(ctx context.Context, messageID int64, workerToken, lastError string, nextAttemptAt int64, permanent bool) (bool, error) {
|
||||
return r.store.Notifications.RetryOutbox(ctx, messageID, workerToken, lastError, nextAttemptAt, permanent)
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,6 +20,59 @@ type accountLoginService struct {
|
||||
server *Server
|
||||
// repository 提供账号登录服务所需的最小凭证持久化能力。
|
||||
repository accountLoginRepository
|
||||
// createApplication 提供已迁移的手动 Cookie 登录应用用例。
|
||||
createApplication *accountapp.LoginService
|
||||
}
|
||||
|
||||
// serverLoginLifecyclePort 将登录成功后的审计、资料刷新和运行时重启适配到应用层端口。
|
||||
type serverLoginLifecyclePort struct {
|
||||
// server 提供现有 Server 运行时与审计适配能力。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// AfterSuccessfulLogin 在凭证写入并释放凭证锁后执行 Server 侧登录后续编排。
|
||||
func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID, method string) {
|
||||
if p.server == nil {
|
||||
return
|
||||
}
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
|
||||
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
|
||||
}
|
||||
|
||||
// serverCookieWriter 将本次请求中的明文 Cookie 限制在 Server 基础设施适配器内。
|
||||
type serverCookieWriter struct {
|
||||
// repository 提供凭证锁、写入和旧 Token 清理能力。
|
||||
repository accountLoginRepository
|
||||
// cookies 保存当前请求明文 Cookie;仅在 CreateOwnedCookie 调用期间使用,不进入应用层模型。
|
||||
cookies string
|
||||
// logger 提供旧 Token 清理失败的脱敏日志能力。
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// CreateOwnedCookie 在凭证锁内原子校验归属、写入 Cookie 并清理旧连接 Token。
|
||||
func (w serverCookieWriter) CreateOwnedCookie(ctx context.Context, accountID string, userID int64) error {
|
||||
if w.repository == nil {
|
||||
return errors.New("账号登录凭证 repository 未初始化")
|
||||
}
|
||||
// unlock 保护凭证写入与旧连接 Token 清理,外部网络和运行时操作在锁外执行。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// writeErr 保存凭证写入错误;归属校验失败时直接返回且不清理 Token。
|
||||
writeErr := w.repository.CreateCookieOwned(ctx, accountID, w.cookies, userID)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;清理失败不回滚已经成功写入的 Cookie。
|
||||
clearErr := w.repository.ClearTokens(ctx, accountID)
|
||||
if clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其 Server 生命周期适配器。
|
||||
func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, error) {
|
||||
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
|
||||
}
|
||||
|
||||
// serverAccountProfilePort 将平台资料刷新适配为账号应用层 Port。
|
||||
@@ -88,30 +142,12 @@ type accountCookieUpdateInput struct {
|
||||
|
||||
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountLoginInput) error {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// unlock 保护账号凭证的创建与后续登录状态清理。
|
||||
unlock := svc.repository.LockCredentials(input.AccountID)
|
||||
// err 表示账号凭证创建错误。
|
||||
if err := svc.repository.CreateCookieOwned(ctx, input.AccountID, input.Cookies, input.UserID); err != nil {
|
||||
unlock()
|
||||
return err
|
||||
if svc == nil || svc.createApplication == nil || svc.server == nil {
|
||||
return errors.New("账号登录应用服务未初始化")
|
||||
}
|
||||
{
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断登录。
|
||||
if err := svc.repository.ClearTokens(ctx, input.AccountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", input.AccountID, "err", err)
|
||||
}
|
||||
}
|
||||
// loginMethod 是归一化后的登录方式。
|
||||
loginMethod := normalizeLoginMethod(input.LoginMethod)
|
||||
if loginMethod == "" {
|
||||
loginMethod = loginMethodManual
|
||||
}
|
||||
s.markSuccessfulLogin(ctx, input.AccountID, input.UserID, loginMethod, "账号登录成功")
|
||||
unlock()
|
||||
svc.refreshAndRestartAccount(ctx, input.UserID, input.AccountID)
|
||||
return nil
|
||||
return svc.createApplication.CreateCookie(ctx, accountapp.CreateCookieInput{
|
||||
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod,
|
||||
}, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger})
|
||||
}
|
||||
|
||||
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
|
||||
@@ -44,12 +44,17 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
if batchRunnerErr != nil {
|
||||
panic(batchRunnerErr)
|
||||
}
|
||||
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
|
||||
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(server)
|
||||
if accountLoginCreateErr != nil {
|
||||
panic(accountLoginCreateErr)
|
||||
}
|
||||
return &applicationServices{
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
|
||||
itemSinglePublish: newItemPublishApplication(server),
|
||||
itemBatchRunner: itemBatchRunner,
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate},
|
||||
accountProfile: accountProfile,
|
||||
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
|
||||
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
|
||||
|
||||
Reference in new issue
Block a user