推进P1聊天通知与凭证应用端口迁移
This commit is contained in:
1 parent
25531c05cb
commit
550aee8aae
17 files changed
+1677
-289
No files matched your search
@@ -6,6 +6,9 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrCredentialConflict 表示凭证写入前后检测到更新版本已变化,调用方应重新读取后重试。
|
||||
var ErrCredentialConflict = errors.New("账号凭证已发生变化,请重试")
|
||||
|
||||
// CreateCookieInput 是手动录入账号 Cookie 用例的非敏感输入;明文 Cookie 由调用方专用端口封装。
|
||||
type CreateCookieInput struct {
|
||||
// AccountID 是待创建的平台账号稳定标识。
|
||||
@@ -16,12 +19,30 @@ type CreateCookieInput struct {
|
||||
LoginMethod string
|
||||
}
|
||||
|
||||
// UpdateCookieInput 是更新既有账号凭证用例的非敏感输入;明文 Cookie 由调用方专用端口封装。
|
||||
type UpdateCookieInput struct {
|
||||
// AccountID 是待更新的平台账号稳定标识。
|
||||
AccountID string
|
||||
// UserID 是当前用户的本地身份标识。
|
||||
UserID int64
|
||||
// LoginMethod 是可选登录方式;空值表示普通凭证替换且不写入登录审计。
|
||||
LoginMethod string
|
||||
// ExpectedRevision 是调用方读取到的最近 Cookie 刷新时间;零值关闭兼容客户端的乐观冲突检查。
|
||||
ExpectedRevision int64
|
||||
}
|
||||
|
||||
// CookieWriter 定义一次性写入账号凭证的端口;实现方负责在最小作用域内持有明文 Cookie。
|
||||
type CookieWriter interface {
|
||||
// CreateOwnedCookie 原子校验账号归属并写入凭证;明文不应进入应用层 DTO 或日志。
|
||||
CreateOwnedCookie(context.Context, string, int64) error
|
||||
}
|
||||
|
||||
// CookieUpdater 定义更新既有账号凭证的专用端口;实现方负责在最小作用域内接收明文 Cookie。
|
||||
type CookieUpdater interface {
|
||||
// UpdateOwnedCookie 原子校验账号归属、可选版本并写入新凭证;明文不应进入应用层输入或日志。
|
||||
UpdateOwnedCookie(context.Context, string, int64, int64) error
|
||||
}
|
||||
|
||||
// LoginLifecyclePort 定义凭证成功写入后的审计、启用、资料刷新和运行时同步边界。
|
||||
type LoginLifecyclePort interface {
|
||||
// AfterSuccessfulLogin 在凭证写入并释放凭证锁后完成后续登录编排。
|
||||
@@ -64,6 +85,31 @@ func (s *LoginService) CreateCookie(ctx context.Context, input CreateCookieInput
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateCookie 执行既有账号的凭证更新;写入成功后才触发登录审计、资料刷新与运行时同步。
|
||||
func (s *LoginService) UpdateCookie(ctx context.Context, input UpdateCookieInput, updater CookieUpdater) error {
|
||||
if s == nil || s.lifecycle == nil {
|
||||
return errors.New("账号登录服务未初始化")
|
||||
}
|
||||
if updater == nil {
|
||||
return errors.New("账号 Cookie 更新端口未初始化")
|
||||
}
|
||||
if strings.TrimSpace(input.AccountID) == "" {
|
||||
return errors.New("缺少账号 ID")
|
||||
}
|
||||
// updateErr 保存凭证适配器完成归属校验、短锁写入和冲突检测后的结果。
|
||||
updateErr := updater.UpdateOwnedCookie(ctx, input.AccountID, input.UserID, input.ExpectedRevision)
|
||||
if updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
// method 是归一化后的登录方式;更新凭证未声明登录方式时必须保持普通替换,不写入登录审计。
|
||||
method := ""
|
||||
if strings.TrimSpace(input.LoginMethod) != "" {
|
||||
method = normalizeLoginMethod(input.LoginMethod)
|
||||
}
|
||||
s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method)
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeLoginMethod 将兼容的登录方式别名归一化为审计使用的稳定值。
|
||||
func normalizeLoginMethod(method string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(method)) {
|
||||
|
||||
@@ -16,6 +16,24 @@ type fakeCookieWriter struct {
|
||||
called bool
|
||||
}
|
||||
|
||||
// fakeCookieUpdater 是更新凭证应用服务测试用的专用端口替身,不接收明文 Cookie。
|
||||
type fakeCookieUpdater struct {
|
||||
// err 是更新端口需要模拟的失败,包括归属失败、版本冲突和持久化失败。
|
||||
err error
|
||||
// accountID 和 userID 保存最近一次更新请求,用于验证应用层只传递非敏感身份。
|
||||
accountID string
|
||||
userID int64
|
||||
called bool
|
||||
}
|
||||
|
||||
// UpdateOwnedCookie 记录更新请求并返回预设结果。
|
||||
func (u *fakeCookieUpdater) UpdateOwnedCookie(_ context.Context, accountID string, userID, _ int64) error {
|
||||
u.called = true
|
||||
u.accountID = accountID
|
||||
u.userID = userID
|
||||
return u.err
|
||||
}
|
||||
|
||||
// CreateOwnedCookie 记录写入请求但不接收明文 Cookie。
|
||||
func (w *fakeCookieWriter) CreateOwnedCookie(_ context.Context, accountID string, userID int64) error {
|
||||
w.called = true
|
||||
@@ -132,3 +150,94 @@ func TestLoginServiceCreateCookiePropagatesOwnershipFailure(t *testing.T) {
|
||||
t.Fatal("归属校验失败时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceUpdateCookieSuccess 验证更新成功后才触发统一登录后续编排。
|
||||
func TestLoginServiceUpdateCookieSuccess(t *testing.T) {
|
||||
// lifecycle 记录更新成功后的审计、资料和运行时同步调用。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// updater 只接收账号身份,不接收明文 Cookie。
|
||||
updater := &fakeCookieUpdater{}
|
||||
// service 保存使用有效生命周期端口构造的登录应用服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// updateErr 保存应用服务返回的更新结果。
|
||||
updateErr := service.UpdateCookie(context.Background(), UpdateCookieInput{AccountID: "acc1", UserID: 7, LoginMethod: "qr_scan"}, updater)
|
||||
if updateErr != nil {
|
||||
t.Fatalf("更新 Cookie 失败: %v", updateErr)
|
||||
}
|
||||
if !updater.called || updater.accountID != "acc1" || updater.userID != 7 {
|
||||
t.Fatalf("更新端口输入异常: %+v", updater)
|
||||
}
|
||||
if lifecycle.calls != 1 || lifecycle.method != "qr_scan" {
|
||||
t.Fatalf("成功更新后未触发正确后续编排: %+v", lifecycle)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceUpdateCookiePropagatesOwnershipFailure 验证归属失败不会触发成功后续编排。
|
||||
func TestLoginServiceUpdateCookiePropagatesOwnershipFailure(t *testing.T) {
|
||||
// ownershipErr 是凭证适配器完成账号归属校验后返回的越权错误。
|
||||
ownershipErr := errors.New("账号不属于当前用户")
|
||||
// lifecycle 用于确认归属失败时不会记录登录成功。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// updater 模拟归属校验失败。
|
||||
updater := &fakeCookieUpdater{err: ownershipErr}
|
||||
// service 保存有效应用服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// updateErr 保存归属失败结果。
|
||||
updateErr := service.UpdateCookie(context.Background(), UpdateCookieInput{AccountID: "other", UserID: 7}, updater)
|
||||
if !errors.Is(updateErr, ownershipErr) {
|
||||
t.Fatalf("应保留归属失败错误,got %v", updateErr)
|
||||
}
|
||||
if lifecycle.calls != 0 {
|
||||
t.Fatal("归属失败时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceUpdateCookiePropagatesVersionConflict 验证并发版本冲突会原样返回并阻止旧响应生效。
|
||||
func TestLoginServiceUpdateCookiePropagatesVersionConflict(t *testing.T) {
|
||||
// lifecycle 用于确认版本冲突不会触发运行时重启。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// updater 模拟凭证快照已被其他请求更新后的冲突结果。
|
||||
updater := &fakeCookieUpdater{err: ErrCredentialConflict}
|
||||
// service 保存有效应用服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// updateErr 保存并发版本冲突结果。
|
||||
updateErr := service.UpdateCookie(context.Background(), UpdateCookieInput{AccountID: "acc1", UserID: 7}, updater)
|
||||
if !errors.Is(updateErr, ErrCredentialConflict) {
|
||||
t.Fatalf("应返回版本冲突,got %v", updateErr)
|
||||
}
|
||||
if lifecycle.calls != 0 {
|
||||
t.Fatal("版本冲突时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginServiceUpdateCookiePropagatesWriteFailure 验证凭证持久化失败不会伪造登录成功。
|
||||
func TestLoginServiceUpdateCookiePropagatesWriteFailure(t *testing.T) {
|
||||
// writeErr 是凭证适配器返回的底层写入故障。
|
||||
writeErr := errors.New("凭证写入失败")
|
||||
// lifecycle 用于确认写入失败时未触发后续编排。
|
||||
lifecycle := &fakeLoginLifecycle{}
|
||||
// updater 模拟数据库写入失败。
|
||||
updater := &fakeCookieUpdater{err: writeErr}
|
||||
// service 保存有效应用服务;serviceErr 保存构造错误。
|
||||
service, serviceErr := NewLoginService(lifecycle)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造登录服务失败: %v", serviceErr)
|
||||
}
|
||||
// updateErr 保存写入失败结果。
|
||||
updateErr := service.UpdateCookie(context.Background(), UpdateCookieInput{AccountID: "acc1", UserID: 7}, updater)
|
||||
if !errors.Is(updateErr, writeErr) {
|
||||
t.Fatalf("应返回凭证写入错误,got %v", updateErr)
|
||||
}
|
||||
if lifecycle.calls != 0 {
|
||||
t.Fatal("写入失败时不应触发登录成功后续编排")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnavailable 表示聊天发送所需的持久化、运行时或图片上传端口未装配。
|
||||
ErrUnavailable = errors.New("聊天发送服务未启用")
|
||||
// ErrOffline 表示目标账号没有可用的在线发送实例。
|
||||
ErrOffline = errors.New("账号当前离线")
|
||||
// ErrSend 表示平台发送动作失败,消息状态已尽力标记为失败。
|
||||
ErrSend = errors.New("聊天消息发送失败")
|
||||
// ErrStatusSave 表示平台动作已成功,但本地发送状态没有保存成功。
|
||||
ErrStatusSave = errors.New("聊天发送状态保存失败")
|
||||
// ErrSendInvalidInput 表示发送用例缺少会话标识或消息内容不符合限制。
|
||||
ErrSendInvalidInput = errors.New("聊天发送参数无效")
|
||||
)
|
||||
|
||||
// OutgoingInput 是发送文字消息的应用层输入,不携带 HTTP 或数据库模型。
|
||||
type OutgoingInput struct {
|
||||
// Session 保存已完成账号归属校验的会话摘要,不包含登录凭证。
|
||||
Session Session
|
||||
// Text 保存待发送的文字内容,应用层会去除首尾空白并限制长度。
|
||||
Text string
|
||||
}
|
||||
|
||||
// ImageInput 是发送图片消息的应用层输入,Data 只在当前请求生命周期内使用。
|
||||
type ImageInput struct {
|
||||
// Session 保存已完成账号归属校验的会话摘要,不包含登录凭证。
|
||||
Session Session
|
||||
// Filename 保存上传文件名,供平台接口识别图片来源。
|
||||
Filename string
|
||||
// ContentType 保存 HTTP 已校验的图片 MIME 类型。
|
||||
ContentType string
|
||||
// Data 保存图片二进制内容,调用完成后不由服务长期持有。
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// ImageUpload 是图片平台适配器返回的非敏感结果。
|
||||
type ImageUpload struct {
|
||||
// URL 保存可供聊天发送的图片地址。
|
||||
URL string
|
||||
}
|
||||
|
||||
// OutgoingRepository 定义发送用例需要的本地消息写入能力。
|
||||
type OutgoingRepository interface {
|
||||
// CreateOutgoing 创建状态为 sending 的文字消息并返回幂等键。
|
||||
CreateOutgoing(ctx context.Context, session Session, text string) (Message, error)
|
||||
// CreateOutgoingMedia 创建状态为 sending 的媒体消息并返回幂等键。
|
||||
CreateOutgoingMedia(ctx context.Context, session Session, messageType, content string) (Message, error)
|
||||
// SetOutgoingStatus 更新外发消息状态并返回最新消息。
|
||||
SetOutgoingStatus(ctx context.Context, accountID, key, status string) (Message, error)
|
||||
}
|
||||
|
||||
// Sender 定义单个在线账号的最小聊天发送能力。
|
||||
type Sender interface {
|
||||
// SendText 发送文本;messageKey 用于将平台旁路事件与待发送消息关联。
|
||||
SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error
|
||||
// SendImage 发送图片;messageKey 用于将平台旁路事件与待发送消息关联。
|
||||
SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error
|
||||
}
|
||||
|
||||
// SenderProvider 按账号标识解析当前在线发送实例。
|
||||
type SenderProvider interface {
|
||||
// Sender 返回指定账号的发送能力;不存在时返回 false。
|
||||
Sender(accountID string) (Sender, bool)
|
||||
}
|
||||
|
||||
// ImageUploader 定义图片上传所需的平台能力。
|
||||
type ImageUploader interface {
|
||||
// UploadChatImage 按账号标识上传图片;凭证读取与刷新由平台适配器内部完成。
|
||||
UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (ImageUpload, error)
|
||||
}
|
||||
|
||||
// NewWithSending 创建同时支持历史查询和实时发送的聊天应用服务。
|
||||
func NewWithSending(repository Repository, outgoing OutgoingRepository, senders SenderProvider, uploader ImageUploader) *Service {
|
||||
return &Service{
|
||||
repository: repository,
|
||||
outgoing: outgoing,
|
||||
senders: senders,
|
||||
uploader: uploader,
|
||||
}
|
||||
}
|
||||
|
||||
// SendText 创建并发送一条文字消息,失败时尽力保留本地 failed 状态。
|
||||
func (s *Service) SendText(ctx context.Context, input OutgoingInput) (*Message, error) {
|
||||
// session 和 text 保存规范化后的会话及消息内容。
|
||||
session, text, err := normalizeOutgoingInput(input.Session, input.Text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil || s.outgoing == nil || s.senders == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
// sender 和 ok 保存目标账号的在线发送句柄及存在性。
|
||||
sender, ok := s.senders.Sender(session.AccountID)
|
||||
if !ok || sender == nil {
|
||||
return nil, ErrOffline
|
||||
}
|
||||
// message 和 err 保存本地待发送消息及持久化错误。
|
||||
message, err := s.outgoing.CreateOutgoing(ctx, session, text)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("保存待发送消息失败: %w", err)
|
||||
}
|
||||
// sendErr 表示平台文字发送失败;失败分支会补写本地 failed 状态。
|
||||
if sendErr := sender.SendText(ctx, session.ChatID, session.BuyerID, text, message.MessageKey); sendErr != nil {
|
||||
// failed 保存平台发送失败后的本地状态;状态保存失败不覆盖原始发送错误。
|
||||
failed, _ := s.outgoing.SetOutgoingStatus(context.Background(), session.AccountID, message.MessageKey, "failed")
|
||||
return messagePointer(failed, message), fmt.Errorf("%w: %v", ErrSend, sendErr)
|
||||
}
|
||||
// sent 和 err 保存平台发送成功后的本地状态及状态持久化错误。
|
||||
sent, err := s.outgoing.SetOutgoingStatus(ctx, session.AccountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
return messagePointer(sent, message), fmt.Errorf("%w: %v", ErrStatusSave, err)
|
||||
}
|
||||
return messagePointer(sent, message), nil
|
||||
}
|
||||
|
||||
// SendImage 上传并发送一条图片消息,失败时尽力保留本地 failed 状态。
|
||||
func (s *Service) SendImage(ctx context.Context, input ImageInput) (*Message, error) {
|
||||
// session 保存规范化后的会话摘要。
|
||||
session, _, err := normalizeOutgoingInput(input.Session, "图片")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil || s.outgoing == nil || s.senders == nil || s.uploader == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if len(input.Data) == 0 {
|
||||
return nil, ErrSendInvalidInput
|
||||
}
|
||||
// sender 和 ok 保存目标账号的在线发送句柄及存在性。
|
||||
sender, ok := s.senders.Sender(session.AccountID)
|
||||
if !ok || sender == nil {
|
||||
return nil, ErrOffline
|
||||
}
|
||||
// upload 和 err 保存图片上传结果及平台错误。
|
||||
upload, err := s.uploader.UploadChatImage(ctx, session.AccountID, input.Filename, input.ContentType, input.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrSend, err)
|
||||
}
|
||||
if strings.TrimSpace(upload.URL) == "" {
|
||||
return nil, fmt.Errorf("%w: 图片上传未返回地址", ErrSend)
|
||||
}
|
||||
// message 和 err 保存图片待发送消息及本地写入错误。
|
||||
message, err := s.outgoing.CreateOutgoingMedia(ctx, session, "image", upload.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("保存待发送图片失败: %w", err)
|
||||
}
|
||||
// sendErr 表示平台图片发送失败;失败分支会补写本地 failed 状态。
|
||||
if sendErr := sender.SendImage(ctx, session.ChatID, session.BuyerID, upload.URL, 0, message.MessageKey); sendErr != nil {
|
||||
// failed 保存图片发送失败后的本地状态。
|
||||
failed, _ := s.outgoing.SetOutgoingStatus(context.Background(), session.AccountID, message.MessageKey, "failed")
|
||||
return messagePointer(failed, message), fmt.Errorf("%w: %v", ErrSend, sendErr)
|
||||
}
|
||||
// sent 和 err 保存图片发送成功后的本地状态及状态持久化错误。
|
||||
sent, err := s.outgoing.SetOutgoingStatus(ctx, session.AccountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
return messagePointer(sent, message), fmt.Errorf("%w: %v", ErrStatusSave, err)
|
||||
}
|
||||
return messagePointer(sent, message), nil
|
||||
}
|
||||
|
||||
// normalizeOutgoingInput 校验发送会话并返回去除首尾空白的文字内容。
|
||||
func normalizeOutgoingInput(session Session, text string) (Session, string, error) {
|
||||
session.AccountID = strings.TrimSpace(session.AccountID)
|
||||
session.ChatID = strings.TrimSpace(session.ChatID)
|
||||
session.BuyerID = strings.TrimSpace(session.BuyerID)
|
||||
text = strings.TrimSpace(text)
|
||||
if session.AccountID == "" || session.ChatID == "" || session.BuyerID == "" || text == "" || len([]rune(text)) > 2000 {
|
||||
return Session{}, "", ErrSendInvalidInput
|
||||
}
|
||||
return session, text, nil
|
||||
}
|
||||
|
||||
// messagePointer 在状态更新返回空值时回退到已创建消息,确保错误响应仍能携带幂等键。
|
||||
func messagePointer(message Message, fallback Message) *Message {
|
||||
if message.MessageKey == "" {
|
||||
message = fallback
|
||||
}
|
||||
return &message
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sendRepository 是实时发送用例使用的内存持久化替身,记录消息状态迁移。
|
||||
type sendRepository struct {
|
||||
// createErr 表示创建待发送消息时要返回的错误。
|
||||
createErr error
|
||||
// statusErr 表示更新发送状态时要返回的错误。
|
||||
statusErr error
|
||||
// message 保存最近一次创建的本地消息。
|
||||
message Message
|
||||
// statuses 保存按调用顺序写入的消息状态。
|
||||
statuses []string
|
||||
}
|
||||
|
||||
// CreateOutgoing 创建测试文字消息。
|
||||
func (r *sendRepository) CreateOutgoing(_ context.Context, session Session, _ string) (Message, error) {
|
||||
if r.createErr != nil {
|
||||
return Message{}, r.createErr
|
||||
}
|
||||
r.message = Message{ID: 1, AccountID: session.AccountID, ChatID: session.ChatID, MessageKey: "local-1", Status: "sending"}
|
||||
return r.message, nil
|
||||
}
|
||||
|
||||
// CreateOutgoingMedia 创建测试媒体消息。
|
||||
func (r *sendRepository) CreateOutgoingMedia(_ context.Context, session Session, _, content string) (Message, error) {
|
||||
if r.createErr != nil {
|
||||
return Message{}, r.createErr
|
||||
}
|
||||
r.message = Message{ID: 2, AccountID: session.AccountID, ChatID: session.ChatID, MessageKey: "local-image", Content: content, Status: "sending"}
|
||||
return r.message, nil
|
||||
}
|
||||
|
||||
// SetOutgoingStatus 记录状态并返回当前消息。
|
||||
func (r *sendRepository) SetOutgoingStatus(_ context.Context, _, _ string, status string) (Message, error) {
|
||||
r.statuses = append(r.statuses, status)
|
||||
if r.statusErr != nil {
|
||||
return Message{}, r.statusErr
|
||||
}
|
||||
r.message.Status = status
|
||||
return r.message, nil
|
||||
}
|
||||
|
||||
// sendProvider 是按账号返回固定发送器的测试替身。
|
||||
type sendProvider struct {
|
||||
// sender 保存测试发送器;为 nil 时模拟离线账号。
|
||||
sender *sendSender
|
||||
}
|
||||
|
||||
// Sender 返回测试发送器或模拟离线。
|
||||
func (p sendProvider) Sender(string) (Sender, bool) {
|
||||
return p.sender, p.sender != nil
|
||||
}
|
||||
|
||||
// sendSender 记录平台发送调用及其预设错误。
|
||||
type sendSender struct {
|
||||
// sendErr 表示平台发送需要返回的错误。
|
||||
sendErr error
|
||||
// sentKey 保存最近一次收到的幂等键。
|
||||
sentKey string
|
||||
// updatedCookie 保存适配器同步的刷新凭证;测试只记录是否调用,不保存真实秘密。
|
||||
updatedCookie bool
|
||||
}
|
||||
|
||||
// SendText 记录文本发送并返回预设错误。
|
||||
func (s *sendSender) SendText(_ context.Context, _, _, _, messageKey string) error {
|
||||
s.sentKey = messageKey
|
||||
return s.sendErr
|
||||
}
|
||||
|
||||
// SendImage 记录图片发送并返回预设错误。
|
||||
func (s *sendSender) SendImage(_ context.Context, _, _, _ string, _ int64, messageKey string) error {
|
||||
s.sentKey = messageKey
|
||||
return s.sendErr
|
||||
}
|
||||
|
||||
// UpdateCookie 记录刷新凭证同步动作,但不保存明文内容。
|
||||
func (s *sendSender) UpdateCookie(string) {
|
||||
s.updatedCookie = true
|
||||
}
|
||||
|
||||
// sendUploader 是图片上传端口的测试替身。
|
||||
type sendUploader struct {
|
||||
// result 保存上传成功后返回的图片地址。
|
||||
result ImageUpload
|
||||
// err 保存上传或凭证刷新阶段需要返回的错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// UploadChatImage 返回预设上传结果,不接收明文 Cookie 参数。
|
||||
func (u sendUploader) UploadChatImage(context.Context, string, string, string, []byte) (ImageUpload, error) {
|
||||
return u.result, u.err
|
||||
}
|
||||
|
||||
// TestSendTextSuccessPreservesIdempotencyKey 验证成功发送会写入 sent 状态并传递本地幂等键。
|
||||
func TestSendTextSuccessPreservesIdempotencyKey(t *testing.T) {
|
||||
// repository、sender 保存实时发送用例的测试端口。
|
||||
repository, sender := &sendRepository{}, &sendSender{}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, nil)
|
||||
// message 和 err 保存应用层返回的消息及错误。
|
||||
message, err := service.SendText(context.Background(), OutgoingInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Text: " 你好 "})
|
||||
if err != nil || message == nil || message.Status != "sent" || sender.sentKey != "local-1" {
|
||||
t.Fatalf("message=%+v err=%v key=%q", message, err, sender.sentKey)
|
||||
}
|
||||
if len(repository.statuses) != 1 || repository.statuses[0] != "sent" {
|
||||
t.Fatalf("statuses=%v", repository.statuses)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendTextFailureMarksMessageFailed 验证平台失败会保留可重试的本地 failed 状态。
|
||||
func TestSendTextFailureMarksMessageFailed(t *testing.T) {
|
||||
// repository、sender 保存发送失败场景的测试端口。
|
||||
repository, sender := &sendRepository{}, &sendSender{sendErr: errors.New("远端拒绝")}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, nil)
|
||||
// message 和 err 保存失败后的本地消息及错误。
|
||||
message, err := service.SendText(context.Background(), OutgoingInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Text: "你好"})
|
||||
if !errors.Is(err, ErrSend) || message == nil || message.Status != "failed" {
|
||||
t.Fatalf("message=%+v err=%v", message, err)
|
||||
}
|
||||
if len(repository.statuses) != 1 || repository.statuses[0] != "failed" {
|
||||
t.Fatalf("statuses=%v", repository.statuses)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendTextStatusFailureReturnsSentMessage 验证平台成功但本地状态写入失败会返回 ErrStatusSave。
|
||||
func TestSendTextStatusFailureReturnsSentMessage(t *testing.T) {
|
||||
// repository 保存状态写入错误;sender 保存成功发送记录。
|
||||
repository, sender := &sendRepository{statusErr: errors.New("数据库不可用")}, &sendSender{}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, nil)
|
||||
// message 和 err 保存状态写入失败的返回值。
|
||||
message, err := service.SendText(context.Background(), OutgoingInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Text: "你好"})
|
||||
if !errors.Is(err, ErrStatusSave) || message == nil || message.MessageKey != "local-1" {
|
||||
t.Fatalf("message=%+v err=%v", message, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendRejectsUnavailableOfflineAndInvalidInputs 验证不可用、离线和非法输入均在访问端口前失败。
|
||||
func TestSendRejectsUnavailableOfflineAndInvalidInputs(t *testing.T) {
|
||||
// session 保存可复用的有效会话参数。
|
||||
session := Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}
|
||||
// cases 描述发送服务边界分支。
|
||||
cases := []struct {
|
||||
// name 标识当前测试分支。
|
||||
name string
|
||||
// service 保存当前分支使用的聊天服务。
|
||||
service *Service
|
||||
// input 保存当前分支使用的发送输入。
|
||||
input OutgoingInput
|
||||
// wantErr 保存预期应用错误。
|
||||
wantErr error
|
||||
}{
|
||||
{name: "unavailable", service: NewWithSending(nil, nil, nil, nil), input: OutgoingInput{Session: session, Text: "你好"}, wantErr: ErrUnavailable},
|
||||
{name: "offline", service: NewWithSending(nil, &sendRepository{}, sendProvider{}, nil), input: OutgoingInput{Session: session, Text: "你好"}, wantErr: ErrOffline},
|
||||
{name: "invalid", service: NewWithSending(nil, &sendRepository{}, sendProvider{sender: &sendSender{}}, nil), input: OutgoingInput{Session: session, Text: ""}, wantErr: ErrSendInvalidInput},
|
||||
}
|
||||
// testCase 表示当前遍历的发送服务边界分支。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// err 保存当前边界分支返回的应用错误。
|
||||
_, err := testCase.service.SendText(context.Background(), testCase.input)
|
||||
if !errors.Is(err, testCase.wantErr) {
|
||||
t.Fatalf("error=%v want=%v", err, testCase.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendImageDoesNotExposeCredentials 验证图片应用端口只接收账号标识,不传递 Cookie 字段。
|
||||
func TestSendImageDoesNotExposeCredentials(t *testing.T) {
|
||||
// repository、sender、uploader 保存图片发送的测试端口。
|
||||
repository, sender := &sendRepository{}, &sendSender{}
|
||||
// uploader 保存固定图片地址的测试上传端口。
|
||||
uploader := sendUploader{result: ImageUpload{URL: "https://cdn.example/image.jpg"}}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, uploader)
|
||||
// message 和 err 保存图片发送结果。
|
||||
message, err := service.SendImage(context.Background(), ImageInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Filename: "a.jpg", ContentType: "image/jpeg", Data: []byte("image")})
|
||||
if err != nil || message == nil || message.Content != "https://cdn.example/image.jpg" || sender.sentKey != "local-image" {
|
||||
t.Fatalf("message=%+v err=%v key=%q", message, err, sender.sentKey)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendImagePropagatesCredentialWritebackFailure 验证平台适配器返回凭证写回错误时不会静默继续发送。
|
||||
func TestSendImagePropagatesCredentialWritebackFailure(t *testing.T) {
|
||||
// repository、sender、uploader 保存凭证写回失败场景的测试端口。
|
||||
repository, sender := &sendRepository{}, &sendSender{}
|
||||
// uploader 保存模拟凭证写回失败的测试上传端口。
|
||||
uploader := sendUploader{err: errors.New("凭证写回失败")}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, uploader)
|
||||
// _, err 保存图片上传适配器返回的确定性错误。
|
||||
_, err := service.SendImage(context.Background(), ImageInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Filename: "a.jpg", ContentType: "image/jpeg", Data: []byte("image")})
|
||||
if !errors.Is(err, ErrSend) || sender.sentKey != "" || len(repository.statuses) != 0 {
|
||||
t.Fatalf("err=%v sentKey=%q statuses=%v", err, sender.sentKey, repository.statuses)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendImageStatusFailureReturnsSentMessage 验证图片平台成功但本地状态写入失败仍返回幂等消息。
|
||||
func TestSendImageStatusFailureReturnsSentMessage(t *testing.T) {
|
||||
// repository、sender、uploader 保存图片状态写入失败场景的测试端口。
|
||||
repository, sender := &sendRepository{statusErr: errors.New("状态写入失败")}, &sendSender{}
|
||||
// uploader 保存固定图片地址的测试上传端口。
|
||||
uploader := sendUploader{result: ImageUpload{URL: "https://cdn.example/image.jpg"}}
|
||||
// service 保存使用测试端口构造的聊天发送服务。
|
||||
service := NewWithSending(nil, repository, sendProvider{sender: sender}, uploader)
|
||||
// message 和 err 保存图片状态写入失败后的返回值。
|
||||
message, err := service.SendImage(context.Background(), ImageInput{Session: Session{AccountID: "acc-1", ChatID: "chat-1", BuyerID: "buyer-1"}, Filename: "a.jpg", ContentType: "image/jpeg", Data: []byte("image")})
|
||||
if !errors.Is(err, ErrStatusSave) || message == nil || message.MessageKey != "local-image" || sender.sentKey != "local-image" {
|
||||
t.Fatalf("message=%+v err=%v key=%q", message, err, sender.sentKey)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,12 @@ type Repository interface {
|
||||
type Service struct {
|
||||
// repository 保存由调用方注入的最小持久化端口。
|
||||
repository Repository
|
||||
// outgoing 保存实时发送用例的本地消息写入端口。
|
||||
outgoing OutgoingRepository
|
||||
// senders 保存按账号解析在线发送实例的端口。
|
||||
senders SenderProvider
|
||||
// uploader 保存图片上传的平台适配端口。
|
||||
uploader ImageUploader
|
||||
}
|
||||
|
||||
// New 创建聊天历史应用服务;空端口会导致构造结果不可用。
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrChannelNotFound 表示通知渠道或账号绑定目标不存在。
|
||||
ErrChannelNotFound = errors.New("通知渠道不存在")
|
||||
// ErrChannelForbidden 表示当前用户无权操作通知渠道或账号绑定。
|
||||
ErrChannelForbidden = errors.New("无权操作通知渠道")
|
||||
// ErrChannelInvalidInput 表示渠道字段、用户归属或绑定参数无效。
|
||||
ErrChannelInvalidInput = errors.New("通知渠道参数无效")
|
||||
// ErrAccountForbidden 表示账号不存在或不属于当前用户。
|
||||
ErrAccountForbidden = errors.New("无权操作账号通知绑定")
|
||||
// ErrNotifierUnavailable 表示测试发送依赖尚未装配。
|
||||
ErrNotifierUnavailable = errors.New("通知器未启用")
|
||||
)
|
||||
|
||||
// ChannelSummary 是通知渠道的非敏感展示模型;它刻意不包含配置 JSON。
|
||||
type ChannelSummary struct {
|
||||
// ID 是渠道稳定标识。
|
||||
ID int64
|
||||
// Name 是用户可识别的渠道名称。
|
||||
Name string
|
||||
// Type 是通知渠道协议类型。
|
||||
Type string
|
||||
// EventTypes 是渠道订阅的事件类型编码。
|
||||
EventTypes string
|
||||
// Enabled 表示渠道是否参与通知投递。
|
||||
Enabled bool
|
||||
// UserID 是渠道所属用户,仅供应用层归属校验和管理员展示。
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// ChannelRecord 是通知渠道更新时由持久化端口返回的内部记录,Config 仅允许留在应用编排与存储边界。
|
||||
type ChannelRecord struct {
|
||||
// ID 是渠道稳定标识。
|
||||
ID int64
|
||||
// Name 是渠道名称。
|
||||
Name string
|
||||
// Type 是渠道协议类型。
|
||||
Type string
|
||||
// Config 是加密存储解密后的配置 JSON,禁止进入 HTTP 或应用响应。
|
||||
Config string
|
||||
// EventTypes 是渠道订阅事件类型编码。
|
||||
EventTypes string
|
||||
// Enabled 表示渠道是否参与通知投递。
|
||||
Enabled bool
|
||||
// UserID 是渠道所属用户。
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// ChannelInput 是创建通知渠道时的业务输入;Config 只用于写入敏感配置。
|
||||
type ChannelInput struct {
|
||||
// Name 是渠道名称。
|
||||
Name string
|
||||
// Type 是渠道协议类型。
|
||||
Type string
|
||||
// Config 是待加密保存的渠道配置 JSON,禁止记录日志或返回响应。
|
||||
Config string
|
||||
// EventTypes 是渠道订阅事件类型编码。
|
||||
EventTypes string
|
||||
// Enabled 表示创建后是否启用渠道。
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// ChannelPatch 是通知渠道的部分更新输入;nil 字段表示保留现值。
|
||||
type ChannelPatch struct {
|
||||
// Name 是可选的新渠道名称。
|
||||
Name *string
|
||||
// Type 是可选的新渠道协议类型。
|
||||
Type *string
|
||||
// Config 是可选的新敏感配置 JSON,禁止记录日志或返回响应。
|
||||
Config *string
|
||||
// EventTypes 是可选的新订阅事件类型编码。
|
||||
EventTypes *string
|
||||
// Enabled 是可选的新启用状态。
|
||||
Enabled *bool
|
||||
}
|
||||
|
||||
// BindingSummary 是账号与通知渠道绑定的非敏感展示模型。
|
||||
type BindingSummary struct {
|
||||
// ID 是绑定记录稳定标识。
|
||||
ID int64
|
||||
// CookieID 是绑定账号标识。
|
||||
CookieID string
|
||||
// ChannelID 是绑定渠道标识。
|
||||
ChannelID int64
|
||||
// ChannelName 是绑定渠道名称。
|
||||
ChannelName string
|
||||
// Enabled 表示绑定是否启用。
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// ChannelRepository 定义通知渠道和账号绑定用例所需的最小持久化端口。
|
||||
type ChannelRepository interface {
|
||||
// ListChannels 查询指定用户的非敏感渠道摘要。
|
||||
ListChannels(ctx context.Context, userID int64) ([]ChannelSummary, error)
|
||||
// GetChannelForUpdate 查询指定用户拥有的渠道完整记录,仅供更新合并使用。
|
||||
GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*ChannelRecord, error)
|
||||
// CreateChannel 保存一条渠道并返回稳定标识。
|
||||
CreateChannel(ctx context.Context, userID int64, input ChannelInput) (int64, error)
|
||||
// UpdateChannel 保存已通过归属校验的完整渠道记录。
|
||||
UpdateChannel(ctx context.Context, userID int64, record ChannelRecord) error
|
||||
// DeleteChannel 删除指定用户拥有的渠道。
|
||||
DeleteChannel(ctx context.Context, channelID, userID int64) error
|
||||
// OwnsChannel 判断渠道是否属于指定用户。
|
||||
OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error)
|
||||
// OwnsAccount 判断账号是否属于指定用户,不读取账号凭证。
|
||||
OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error)
|
||||
// ListBindings 查询指定用户的非敏感绑定摘要。
|
||||
ListBindings(ctx context.Context, userID int64) ([]BindingSummary, error)
|
||||
// GetBindingIDs 查询账号当前启用的渠道标识。
|
||||
GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error)
|
||||
// SetBindings 覆盖保存账号的渠道绑定。
|
||||
SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error
|
||||
// SetSingleBinding 更新单个账号渠道绑定状态。
|
||||
SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error
|
||||
// DeleteBinding 删除指定用户的一条绑定。
|
||||
DeleteBinding(ctx context.Context, userID, bindingID int64) error
|
||||
// DeleteAccountBindings 删除指定用户账号的全部绑定。
|
||||
DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error
|
||||
}
|
||||
|
||||
// ChannelSender 定义测试通知发送能力,避免应用层依赖具体通知器。
|
||||
type ChannelSender interface {
|
||||
// SendToChannel 向指定渠道发送测试正文。
|
||||
SendToChannel(channelID int64, body string) error
|
||||
}
|
||||
|
||||
// ChannelService 编排通知渠道 CRUD、账号绑定和测试发送,不依赖 HTTP 或数据库模型。
|
||||
type ChannelService struct {
|
||||
// repository 保存渠道与绑定的最小持久化端口。
|
||||
repository ChannelRepository
|
||||
// sender 保存测试通知发送端口;普通 CRUD 不依赖该端口。
|
||||
sender ChannelSender
|
||||
}
|
||||
|
||||
// NewChannelService 构造通知渠道应用服务。
|
||||
func NewChannelService(repository ChannelRepository, sender ChannelSender) *ChannelService {
|
||||
return &ChannelService{repository: repository, sender: sender}
|
||||
}
|
||||
|
||||
// ListChannels 查询用户拥有的非敏感通知渠道摘要。
|
||||
func (s *ChannelService) ListChannels(ctx context.Context, userID int64) ([]ChannelSummary, error) {
|
||||
if s == nil || s.repository == nil || userID <= 0 {
|
||||
return nil, ErrChannelInvalidInput
|
||||
}
|
||||
return s.repository.ListChannels(ctx, userID)
|
||||
}
|
||||
|
||||
// CreateChannel 校验并创建通知渠道;敏感配置只向持久化端口传递。
|
||||
func (s *ChannelService) CreateChannel(ctx context.Context, userID int64, input ChannelInput) (int64, error) {
|
||||
if s == nil || s.repository == nil || userID <= 0 {
|
||||
return 0, ErrChannelInvalidInput
|
||||
}
|
||||
// validationErr 表示创建输入的名称和协议类型校验结果。
|
||||
if validationErr := validateChannelFields(input.Name, input.Type); validationErr != nil {
|
||||
return 0, validationErr
|
||||
}
|
||||
return s.repository.CreateChannel(ctx, userID, input)
|
||||
}
|
||||
|
||||
// UpdateChannel 合并部分更新、校验最终字段并保存用户拥有的渠道。
|
||||
func (s *ChannelService) UpdateChannel(ctx context.Context, userID, channelID int64, patch ChannelPatch) error {
|
||||
if s == nil || s.repository == nil || userID <= 0 || channelID <= 0 {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
// record 保存已通过归属查询的渠道记录;lookupErr 保存读取失败原因。
|
||||
record, lookupErr := s.repository.GetChannelForUpdate(ctx, channelID, userID)
|
||||
if lookupErr != nil {
|
||||
return lookupErr
|
||||
}
|
||||
if record == nil {
|
||||
return ErrChannelForbidden
|
||||
}
|
||||
if patch.Name != nil {
|
||||
record.Name = *patch.Name
|
||||
}
|
||||
if patch.Type != nil {
|
||||
record.Type = *patch.Type
|
||||
}
|
||||
if patch.Config != nil {
|
||||
record.Config = *patch.Config
|
||||
}
|
||||
if patch.EventTypes != nil {
|
||||
record.EventTypes = *patch.EventTypes
|
||||
}
|
||||
if patch.Enabled != nil {
|
||||
record.Enabled = *patch.Enabled
|
||||
}
|
||||
// validationErr 表示合并后的渠道名称和协议类型校验结果。
|
||||
if validationErr := validateChannelFields(record.Name, record.Type); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
record.UserID = userID
|
||||
return s.repository.UpdateChannel(ctx, userID, *record)
|
||||
}
|
||||
|
||||
// DeleteChannel 删除用户拥有的通知渠道。
|
||||
func (s *ChannelService) DeleteChannel(ctx context.Context, userID, channelID int64) error {
|
||||
if s == nil || s.repository == nil || userID <= 0 || channelID <= 0 {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
return s.repository.DeleteChannel(ctx, channelID, userID)
|
||||
}
|
||||
|
||||
// TestChannel 校验渠道归属并发送固定格式测试通知;body 不包含渠道配置或凭证。
|
||||
func (s *ChannelService) TestChannel(ctx context.Context, userID, channelID int64, now time.Time) error {
|
||||
if s == nil || s.repository == nil || userID <= 0 || channelID <= 0 {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
if s.sender == nil {
|
||||
return ErrNotifierUnavailable
|
||||
}
|
||||
// owned 表示渠道归属结果;ownershipErr 保存归属查询失败原因。
|
||||
owned, ownershipErr := s.repository.OwnsChannel(ctx, channelID, userID)
|
||||
if ownershipErr != nil {
|
||||
return ownershipErr
|
||||
}
|
||||
if !owned {
|
||||
return ErrChannelForbidden
|
||||
}
|
||||
if now.IsZero() {
|
||||
now = time.Now()
|
||||
}
|
||||
// body 是固定测试通知正文,不包含渠道敏感配置。
|
||||
body := fmt.Sprintf("🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: %s", now.Format("2006-01-02 15:04:05"))
|
||||
return s.sender.SendToChannel(channelID, body)
|
||||
}
|
||||
|
||||
// ListBindings 查询用户所有账号的非敏感通知绑定。
|
||||
func (s *ChannelService) ListBindings(ctx context.Context, userID int64) ([]BindingSummary, error) {
|
||||
if s == nil || s.repository == nil || userID <= 0 {
|
||||
return nil, ErrChannelInvalidInput
|
||||
}
|
||||
return s.repository.ListBindings(ctx, userID)
|
||||
}
|
||||
|
||||
// GetBindingIDs 校验账号归属后查询其启用渠道 ID。
|
||||
func (s *ChannelService) GetBindingIDs(ctx context.Context, userID int64, cookieID string) ([]int64, error) {
|
||||
// validationErr 表示账号归属校验结果。
|
||||
if validationErr := s.validateAccount(ctx, userID, cookieID); validationErr != nil {
|
||||
return nil, validationErr
|
||||
}
|
||||
return s.repository.GetBindingIDs(ctx, cookieID)
|
||||
}
|
||||
|
||||
// SetBindings 校验账号和全部渠道归属后覆盖保存绑定。
|
||||
func (s *ChannelService) SetBindings(ctx context.Context, userID int64, cookieID string, channelIDs []int64) error {
|
||||
// validationErr 表示账号归属校验结果。
|
||||
if validationErr := s.validateAccount(ctx, userID, cookieID); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
// channelID 表示当前待校验归属的渠道。
|
||||
for _, channelID := range channelIDs {
|
||||
// owned 表示渠道归属结果;ownershipErr 保存归属查询失败原因。
|
||||
owned, ownershipErr := s.repository.OwnsChannel(ctx, channelID, userID)
|
||||
if ownershipErr != nil {
|
||||
return ownershipErr
|
||||
}
|
||||
if !owned {
|
||||
return ErrChannelForbidden
|
||||
}
|
||||
}
|
||||
return s.repository.SetBindings(ctx, cookieID, channelIDs)
|
||||
}
|
||||
|
||||
// SetSingleBinding 校验账号和渠道归属后更新单条绑定状态。
|
||||
func (s *ChannelService) SetSingleBinding(ctx context.Context, userID int64, cookieID string, channelID int64, enabled bool) error {
|
||||
// validationErr 表示账号归属校验结果。
|
||||
if validationErr := s.validateAccount(ctx, userID, cookieID); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
// owned 表示渠道归属结果;ownershipErr 保存归属查询失败原因。
|
||||
owned, ownershipErr := s.repository.OwnsChannel(ctx, channelID, userID)
|
||||
if ownershipErr != nil {
|
||||
return ownershipErr
|
||||
}
|
||||
if !owned {
|
||||
return ErrChannelForbidden
|
||||
}
|
||||
return s.repository.SetSingleBinding(ctx, cookieID, channelID, enabled)
|
||||
}
|
||||
|
||||
// DeleteBinding 删除用户的一条绑定,归属由持久化端口再次约束。
|
||||
func (s *ChannelService) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
|
||||
if s == nil || s.repository == nil || userID <= 0 || bindingID <= 0 {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
return s.repository.DeleteBinding(ctx, userID, bindingID)
|
||||
}
|
||||
|
||||
// DeleteAccountBindings 校验账号归属后删除其全部绑定。
|
||||
func (s *ChannelService) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
|
||||
// validationErr 表示账号归属校验结果。
|
||||
if validationErr := s.validateAccount(ctx, userID, cookieID); validationErr != nil {
|
||||
return validationErr
|
||||
}
|
||||
return s.repository.DeleteAccountBindings(ctx, userID, cookieID)
|
||||
}
|
||||
|
||||
// validateAccount 校验用户和账号标识,并确保端口返回的结果属于当前用户。
|
||||
func (s *ChannelService) validateAccount(ctx context.Context, userID int64, cookieID string) error {
|
||||
if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(cookieID) == "" {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
// owned 表示账号归属结果;ownershipErr 保存归属查询失败原因。
|
||||
owned, ownershipErr := s.repository.OwnsAccount(ctx, userID, cookieID)
|
||||
if ownershipErr != nil {
|
||||
return ownershipErr
|
||||
}
|
||||
if !owned {
|
||||
return ErrAccountForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateChannelFields 校验业务必填字段,避免将无名或无类型渠道写入存储。
|
||||
func validateChannelFields(name, channelType string) error {
|
||||
if strings.TrimSpace(name) == "" || strings.TrimSpace(channelType) == "" {
|
||||
return ErrChannelInvalidInput
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package notifications
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// channelRepositoryStub 是通知渠道应用服务测试使用的可控端口替身。
|
||||
type channelRepositoryStub struct {
|
||||
// summaries 保存列表查询返回的非敏感渠道摘要。
|
||||
summaries []ChannelSummary
|
||||
// record 保存更新查询返回的渠道记录。
|
||||
record *ChannelRecord
|
||||
// bindings 保存绑定列表查询结果。
|
||||
bindings []BindingSummary
|
||||
// bindingIDs 保存账号启用的渠道 ID。
|
||||
bindingIDs []int64
|
||||
// ownedChannel 表示渠道归属校验结果。
|
||||
ownedChannel bool
|
||||
// ownedAccount 表示账号归属校验结果。
|
||||
ownedAccount bool
|
||||
// err 保存端口操作失败原因。
|
||||
err error
|
||||
// createdInput 保存最近一次创建输入,便于验证敏感值只进入端口。
|
||||
createdInput ChannelInput
|
||||
// updatedRecord 保存最近一次更新记录,便于验证部分更新合并。
|
||||
updatedRecord *ChannelRecord
|
||||
// sentBindings 保存最近一次覆盖绑定请求。
|
||||
sentBindings []int64
|
||||
}
|
||||
|
||||
// ListChannels 返回预置渠道摘要。
|
||||
func (r *channelRepositoryStub) ListChannels(context.Context, int64) ([]ChannelSummary, error) {
|
||||
return r.summaries, r.err
|
||||
}
|
||||
|
||||
// GetChannelForUpdate 返回预置渠道完整记录。
|
||||
func (r *channelRepositoryStub) GetChannelForUpdate(context.Context, int64, int64) (*ChannelRecord, error) {
|
||||
return r.record, r.err
|
||||
}
|
||||
|
||||
// CreateChannel 记录创建输入并返回固定渠道 ID。
|
||||
func (r *channelRepositoryStub) CreateChannel(_ context.Context, _ int64, input ChannelInput) (int64, error) {
|
||||
r.createdInput = input
|
||||
if r.err != nil {
|
||||
return 0, r.err
|
||||
}
|
||||
return 41, nil
|
||||
}
|
||||
|
||||
// UpdateChannel 记录更新后的完整渠道记录。
|
||||
func (r *channelRepositoryStub) UpdateChannel(_ context.Context, _ int64, record ChannelRecord) error {
|
||||
r.updatedRecord = &record
|
||||
return r.err
|
||||
}
|
||||
|
||||
// DeleteChannel 返回预置端口错误。
|
||||
func (r *channelRepositoryStub) DeleteChannel(context.Context, int64, int64) error { return r.err }
|
||||
|
||||
// OwnsChannel 返回预置渠道归属结果。
|
||||
func (r *channelRepositoryStub) OwnsChannel(context.Context, int64, int64) (bool, error) {
|
||||
return r.ownedChannel, r.err
|
||||
}
|
||||
|
||||
// OwnsAccount 返回预置账号归属结果。
|
||||
func (r *channelRepositoryStub) OwnsAccount(context.Context, int64, string) (bool, error) {
|
||||
return r.ownedAccount, r.err
|
||||
}
|
||||
|
||||
// ListBindings 返回预置绑定摘要。
|
||||
func (r *channelRepositoryStub) ListBindings(context.Context, int64) ([]BindingSummary, error) {
|
||||
return r.bindings, r.err
|
||||
}
|
||||
|
||||
// GetBindingIDs 返回预置账号绑定 ID。
|
||||
func (r *channelRepositoryStub) GetBindingIDs(context.Context, string) ([]int64, error) {
|
||||
return r.bindingIDs, r.err
|
||||
}
|
||||
|
||||
// SetBindings 记录覆盖绑定请求。
|
||||
func (r *channelRepositoryStub) SetBindings(_ context.Context, _ string, channelIDs []int64) error {
|
||||
r.sentBindings = append([]int64(nil), channelIDs...)
|
||||
return r.err
|
||||
}
|
||||
|
||||
// SetSingleBinding 返回预置端口错误。
|
||||
func (r *channelRepositoryStub) SetSingleBinding(context.Context, string, int64, bool) error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// DeleteBinding 返回预置端口错误。
|
||||
func (r *channelRepositoryStub) DeleteBinding(context.Context, int64, int64) error { return r.err }
|
||||
|
||||
// DeleteAccountBindings 返回预置端口错误。
|
||||
func (r *channelRepositoryStub) DeleteAccountBindings(context.Context, int64, string) error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// channelSenderStub 是测试发送端口的替身。
|
||||
type channelSenderStub struct {
|
||||
// body 保存最近一次发送的正文。
|
||||
body string
|
||||
// err 保存发送失败原因。
|
||||
err error
|
||||
}
|
||||
|
||||
// SendToChannel 记录发送正文并返回预置错误。
|
||||
func (s *channelSenderStub) SendToChannel(_ int64, body string) error {
|
||||
s.body = body
|
||||
return s.err
|
||||
}
|
||||
|
||||
// TestChannelServiceCreatesAndUpdatesWithoutReturningConfig 验证渠道创建更新成功且配置不进入展示模型。
|
||||
func TestChannelServiceCreatesAndUpdatesWithoutReturningConfig(t *testing.T) {
|
||||
// repository 是保存敏感配置但不把它放入摘要的端口替身。
|
||||
repository := &channelRepositoryStub{summaries: []ChannelSummary{{ID: 1, Name: "邮件", Type: "email"}}, record: &ChannelRecord{ID: 1, Name: "旧名", Type: "email", Config: `{"password":"secret"}`, Enabled: true}}
|
||||
// service 是待验证的通知渠道应用服务。
|
||||
service := NewChannelService(repository, nil)
|
||||
// channelID、createErr 保存创建结果。
|
||||
channelID, createErr := service.CreateChannel(context.Background(), 7, ChannelInput{Name: "邮件", Type: "email", Config: `{"password":"secret"}`})
|
||||
if createErr != nil || channelID != 41 || repository.createdInput.Config == "" {
|
||||
t.Fatalf("创建结果异常: id=%d err=%v", channelID, createErr)
|
||||
}
|
||||
// name 保存部分更新后的渠道名称。
|
||||
name := "新名"
|
||||
// updateErr 保存更新结果。
|
||||
updateErr := service.UpdateChannel(context.Background(), 7, 1, ChannelPatch{Name: &name})
|
||||
if updateErr != nil || repository.updatedRecord == nil || repository.updatedRecord.Name != "新名" || repository.updatedRecord.Config != `{"password":"secret"}` {
|
||||
t.Fatalf("更新结果异常: record=%+v err=%v", repository.updatedRecord, updateErr)
|
||||
}
|
||||
// summaries、listErr 保存非敏感渠道列表结果。
|
||||
summaries, listErr := service.ListChannels(context.Background(), 7)
|
||||
if listErr != nil || len(summaries) != 1 || summaries[0].Name != "邮件" {
|
||||
t.Fatalf("列表结果异常: summaries=%+v err=%v", summaries, listErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChannelServiceRejectsOwnershipAndStorageFailures 验证归属失败和存储错误不会继续写入。
|
||||
func TestChannelServiceRejectsOwnershipAndStorageFailures(t *testing.T) {
|
||||
// forbiddenRepository 是拒绝渠道归属的端口替身。
|
||||
forbiddenRepository := &channelRepositoryStub{ownedChannel: false, ownedAccount: false}
|
||||
// forbiddenService 是使用拒绝归属端口的应用服务。
|
||||
forbiddenService := NewChannelService(forbiddenRepository, &channelSenderStub{})
|
||||
// forbiddenErr 保存测试发送的归属错误。
|
||||
forbiddenErr := forbiddenService.TestChannel(context.Background(), 7, 1, time.Unix(0, 0))
|
||||
if !errors.Is(forbiddenErr, ErrChannelForbidden) {
|
||||
t.Fatalf("渠道归属失败错误异常: %v", forbiddenErr)
|
||||
}
|
||||
// bindingErr 保存账号绑定的归属错误。
|
||||
bindingErr := forbiddenService.SetBindings(context.Background(), 7, "acc", []int64{1})
|
||||
if !errors.Is(bindingErr, ErrAccountForbidden) {
|
||||
t.Fatalf("账号归属失败错误异常: %v", bindingErr)
|
||||
}
|
||||
// storageError 是持久化端口失败原因。
|
||||
storageError := errors.New("storage failed")
|
||||
// storageRepository 是返回存储错误的端口替身。
|
||||
storageRepository := &channelRepositoryStub{ownedChannel: true, ownedAccount: true, err: storageError, record: &ChannelRecord{Name: "x", Type: "webhook"}}
|
||||
// storageService 是使用存储错误端口的应用服务。
|
||||
storageService := NewChannelService(storageRepository, &channelSenderStub{})
|
||||
// updateErr 保存存储错误传播结果。
|
||||
updateErr := storageService.UpdateChannel(context.Background(), 7, 1, ChannelPatch{})
|
||||
if !errors.Is(updateErr, storageError) {
|
||||
t.Fatalf("存储错误未透传: %v", updateErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChannelServiceTestSendUsesSafeBody 验证测试发送只生成固定正文,不携带渠道配置。
|
||||
func TestChannelServiceTestSendUsesSafeBody(t *testing.T) {
|
||||
// repository 是允许渠道归属且不返回敏感配置的端口替身。
|
||||
repository := &channelRepositoryStub{ownedChannel: true}
|
||||
// sender 是记录测试正文的通知发送替身。
|
||||
sender := &channelSenderStub{}
|
||||
// service 是待验证的测试发送应用服务。
|
||||
service := NewChannelService(repository, sender)
|
||||
// sendErr 保存测试发送结果。
|
||||
sendErr := service.TestChannel(context.Background(), 7, 1, time.Unix(0, 0).UTC())
|
||||
if sendErr != nil || !strings.Contains(sender.body, "通知渠道测试") || strings.Contains(sender.body, "password") {
|
||||
t.Fatalf("测试正文异常: body=%q err=%v", sender.body, sendErr)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user