推进P1聊天通知与凭证应用端口迁移
This commit is contained in:
1 parent
25531c05cb
commit
550aee8aae
17 files changed
+1677
-289
No files matched your search
@@ -95,12 +95,12 @@ app shell / routes
|
||||
| 1. PR CI 与测试基础 | 已完成 | 独立 CI、测试 DB 模板、可执行 race | CI、独立模板、server smoke race 和完整 race 均有验证 |
|
||||
| 2. 敏感数据访问边界 | 已完成 | 摘要、凭证、登录秘密和系统设置分离 | Cookie/平台运行视图、系统设置脱敏读写、已知生产敏感设置调用方审计和运维诊断输出脱敏已收口;SQLite、MySQL 8.4、PostgreSQL 17 的真实多库迁移与 CRUD 回归均通过;高频运行时仅读取窄视图、不逐次写审计,管理/一次性敏感读取均有审计和 fail-closed 测试 |
|
||||
| 3. HTTP API 契约 | 已完成 | 统一错误、具名 DTO、版本化路径 | 统一错误 DTO、具名成功 DTO、所有前端业务调用方版本化、旧路径兼容和最终审计均已完成 |
|
||||
| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单、单/批量商品发布、账号资料刷新、手动/扫码登录、聊天历史和通知 uncertain 查询已通过应用 Port 接入;更新凭证、聊天写入及部分商品辅助流程仍由 Server 持有,handler 的低层依赖与其他领域 Port 仍待收口 |
|
||||
| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单、单/批量商品发布、账号资料刷新、手动/扫码登录、普通 Cookie 更新、聊天历史/写入和通知渠道/绑定/uncertain 查询已通过应用 Port 接入;密码登录、其他账号操作、部分商品辅助流程仍待迁移,handler 的低层依赖与其他领域 Port 仍待收口 |
|
||||
| 5. 应用生命周期装配 | 进行中 | 消除必需依赖 setter 回填并统一关闭边界 | Server、续期调度器、浏览器 Manager、Engine watcher、账号 Manager 的 Stop/Close 已具备 Context/fencing 与回归;Server 后台/恢复任务已有进程内 ID、状态和 Context 超时查询,删除任务仍同步执行且进程重启不保留历史,统一跨组件清单仍待补齐 |
|
||||
| 6. Engine 与 Automation | 已完成 | facade + 独立状态组件 | Engine/Automation 组件边界、race、生命周期与冻结规范测试均已通过 |
|
||||
| 7. React Feature 化 | 进行中 | 页面、Hook、API、类型按领域拆分 | Rules、Items、Accounts、Cards、Orders、Notifications、Dashboard、Settings、Chat 和 AccountAutomation 的 feature/API/Hook 已拆分,App 路由懒加载和入口包体预算已收口;Provider/路由壳、完整页面行为覆盖和剩余大型页面边界仍待完成 |
|
||||
| 8. DB 与事务治理 | 进行中 | 窄接口、事务执行器、方言门禁 | 订单/商品/通知应用 Port、批量 worker、订单 reconciliation、通知 uncertain 状态和三库迁移证据已补齐;任务状态明确为非持久化进程内元数据;仍有 Server 低层适配集中、`sql.Tx`/`db.*` 旧边界、更多批量读写与补偿查询待收口 |
|
||||
| 9. 架构门禁与兼容清理 | 进行中 | 允许依赖图、临时例外、兼容路径退场 | `architecturecheck` 已覆盖应用 Port AST 类型和 Server 新增低层依赖;仍保留历史 Server 临时白名单,密码/扫码/聊天等 Port、旧 API 遥测和 Sunset 条件尚未完成 |
|
||||
| 8. DB 与事务治理 | 进行中 | 窄接口、事务执行器、方言门禁 | 订单/商品/通知应用 Port、批量 worker、订单 reconciliation、通知渠道/绑定与 uncertain 状态和三库迁移证据已补齐;任务状态明确为非持久化进程内元数据;仍有 Server 低层适配集中、`sql.Tx`/`db.*` 旧边界、更多批量读写与补偿查询待收口 |
|
||||
| 9. 架构门禁与兼容清理 | 进行中 | 允许依赖图、临时例外、兼容路径退场 | `architecturecheck` 已覆盖应用 Port AST 类型和 Server 新增低层依赖;聊天写入、通知渠道/绑定和普通 Cookie 更新已接入 Port,但仍保留历史 Server 临时白名单,密码登录、其他账号操作、旧 API 遥测和 Sunset 条件尚未完成 |
|
||||
| 10. 注释基线清零 | 进行中 | 全仓准确中文注释检查 | 已有字符级/AST 门禁;待完成模板短语黑名单、业务语义抽查、复杂度门禁和冻结文件精确例外 |
|
||||
|
||||
### 当前执行入口
|
||||
@@ -800,6 +800,7 @@ npm --prefix frontend run build
|
||||
| 2026-08-16 | P1 自动化调度器结果收口切片 | 已完成本切片 | 恢复扫描、延迟任务和异常规则处理不再吞 `Claim/Finish/Postpone/Quarantine` 落库错误;外部动作或状态收口失败统一保留原始错误、`needs_review` 和隔离错误,新增隔离成功/失败与非法延迟状态回归。Automation 全量、架构和中文注释门禁通过;账号任务及其他旁路仍待继续盘点 |
|
||||
| 2026-08-16 | P1 通知 uncertain 查询应用 Port 切片 | 已完成本切片 | 新增纯应用层通知 uncertain DTO、归属隔离 Repository/Service;用户与管理员查询 handler 仅做 DB→应用→HTTP 适配,不再直接编排数据库查询;保留正文、错误原文、渠道配置和凭证不出边界,应用/Server 回归、架构和中文注释门禁通过 |
|
||||
| 2026-08-16 | P1 Server 后台任务生命周期登记切片 | 已完成本切片 | 新增进程内有限历史任务注册表、任务 ID、running/succeeded/failed/canceled/timed_out 状态和管理员 `/api/v1/admin/tasks` 查询;订单/商品/补偿恢复扫描器使用显式 Context 登记,关闭等待仍受 backgroundWG/Context 约束;不新增 DB 迁移,历史随进程重启清空,补充状态/超时/HTTP/WaitForBackground 回归 |
|
||||
| 2026-08-16 | P1 应用 Port 与凭证协调增量切片:聊天写入、通知渠道/绑定、普通 Cookie 更新 | 已完成本切片 | 新增聊天文字/图片发送、幂等状态收口和在线账号发送 Port;新增通知渠道 CRUD、测试发送、账号绑定及 uncertain 查询的应用服务与具名 DTO;新增普通 Cookie 更新 `LoginService.UpdateCookie`,由 request-scoped 凭证适配器在短锁内复核归属、执行兼容 `last_refresh_at` 冲突检查、写入 Cookie 和清理旧 Token,解锁后才执行审计/资料刷新/运行时同步;应用、Server 回归,`go test ./...`,Server race,架构/Go/前端注释门禁,前端 369 个测试、类型检查和生产构建均通过;本机未配置 `TEST_MYSQL_URL`/`TEST_POSTGRES_URL`,本切片未执行外部数据库实测。该记录只关闭三个子切片,P1 应用 Port、凭证协调、阶段 4/5/8/9 仍保持“进行中”;`ListChannels` 适配器仍会读取并丢弃 Config,完整凭证协调及其他 Server 低层依赖待后续收口 |
|
||||
| 2026-08-15 | P1 扫码登录应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层扫码登录 DTO、凭证 Repository 和生命周期 Port;Server 仅负责平台结果转换、会话幂等和基础设施适配,扫码新建/更新、归属校验、Cookie 快照合并及旧 Token 清理由应用服务编排;新增成功、跨用户、目标不一致、写入失败、清理失败和敏感结果不泄露测试,账号/Server 回归、架构门禁和中文注释门禁通过。更新凭证及其他账号操作仍待迁移 |
|
||||
| 2026-08-15 | P1 聊天历史应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层聊天消息/会话分页 DTO、最小 Repository 和 Service;聊天历史 handler 完成实际接入,旧 communication service/repository 不再持有历史查询职责;新增用户归属、参数校验、未装配依赖、底层失败和会话摘要失败测试,Server、架构和中文注释门禁通过。聊天写入与实时会话编排仍待迁移 |
|
||||
| 2026-08-15 | P1 通知不确定态运维可见性切片 | 已完成本切片 | 新增按用户/管理员隔离的 uncertain outbox 元数据查询、计数和版本化 HTTP 接口;响应不返回通知正文、渠道配置、错误原文或凭证;补充 SQLite 隔离、管理员汇总、非管理员 403、脱敏和 limit 回归,DB/Server、架构和中文注释门禁通过。更多统一运维任务清单和旧入口退场仍待完成 |
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,12 @@ func (r storeAccountLoginRepository) LoadPlatformDetail(ctx context.Context, acc
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}, nil
|
||||
// summary 只补充非敏感版本字段,避免为乐观冲突检查读取或解密登录密码。
|
||||
summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID)
|
||||
if summaryErr != nil {
|
||||
return nil, summaryErr
|
||||
}
|
||||
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt}, nil
|
||||
}
|
||||
|
||||
// UpdateFlatCookieOwned 委托扁平 Cookie 更新并清除旧的完整 Cookie Jar 快照。
|
||||
|
||||
@@ -36,7 +36,9 @@ func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, user
|
||||
if p.server == nil {
|
||||
return
|
||||
}
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
|
||||
if strings.TrimSpace(method) != "" {
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
|
||||
}
|
||||
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
|
||||
}
|
||||
|
||||
@@ -71,6 +73,36 @@ func (w serverCookieWriter) CreateOwnedCookie(ctx context.Context, accountID str
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、Cookie 写入和旧 Token 清理;慢速资料刷新由应用服务在解锁后触发。
|
||||
func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error {
|
||||
if w.repository == nil {
|
||||
return errors.New("账号登录凭证 repository 未初始化")
|
||||
}
|
||||
// unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时操作。
|
||||
unlock := w.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
// detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。
|
||||
detail, loadErr := w.repository.LoadPlatformDetail(ctx, accountID)
|
||||
if loadErr != nil {
|
||||
return loadErr
|
||||
}
|
||||
if detail == nil || detail.UserID != userID {
|
||||
return db.ErrForbidden
|
||||
}
|
||||
if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision {
|
||||
return accountapp.ErrCredentialConflict
|
||||
}
|
||||
// updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。
|
||||
if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。
|
||||
if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil {
|
||||
w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其 Server 生命周期适配器。
|
||||
func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, error) {
|
||||
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
|
||||
@@ -144,6 +176,8 @@ type accountCookieUpdateInput struct {
|
||||
UserID int64
|
||||
// LoginMethod 是可选的登录方式。
|
||||
LoginMethod string
|
||||
// ExpectedRevision 是客户端读取到的最近 Cookie 刷新时间,用于检测并发覆盖。
|
||||
ExpectedRevision int64
|
||||
}
|
||||
|
||||
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
@@ -158,37 +192,12 @@ func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountL
|
||||
|
||||
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// unlock 保护账号凭证更新、连接凭证清理和登录审计。
|
||||
unlock := svc.repository.LockCredentials(input.AccountID)
|
||||
// detail 和 err 保存账号凭证详情查询结果。
|
||||
detail, err := s.loadCookiePlatformDetail(ctx, input.AccountID)
|
||||
if err != nil || detail == nil || detail.UserID != input.UserID {
|
||||
unlock()
|
||||
if err == nil {
|
||||
return db.ErrNotFound
|
||||
}
|
||||
return err
|
||||
if svc == nil || svc.createApplication == nil || svc.server == nil {
|
||||
return errors.New("账号登录应用服务未初始化")
|
||||
}
|
||||
// err 表示扁平 Cookie 更新错误。
|
||||
if err := svc.repository.UpdateFlatCookieOwned(ctx, detail, input.Cookies); err != nil {
|
||||
unlock()
|
||||
return err
|
||||
}
|
||||
{
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断登录。
|
||||
if err := svc.repository.ClearTokens(ctx, input.AccountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", input.AccountID, "err", err)
|
||||
}
|
||||
}
|
||||
// loginMethod 是可选的归一化登录方式。
|
||||
if loginMethod := normalizeLoginMethod(input.LoginMethod); loginMethod != "" {
|
||||
s.markSuccessfulLogin(ctx, input.AccountID, input.UserID, loginMethod, "账号登录成功")
|
||||
}
|
||||
unlock()
|
||||
svc.refreshAndRestartAccount(ctx, input.UserID, input.AccountID)
|
||||
return nil
|
||||
return svc.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{
|
||||
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, ExpectedRevision: input.ExpectedRevision,
|
||||
}, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger})
|
||||
}
|
||||
|
||||
// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。
|
||||
|
||||
@@ -28,6 +28,8 @@ type applicationServices struct {
|
||||
chat *chatapp.Service
|
||||
// uncertainNotifications 是通知不确定状态运维查询应用服务。
|
||||
uncertainNotifications *notificationsapp.Service
|
||||
// notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。
|
||||
notificationChannels *notificationsapp.ChannelService
|
||||
// analytics 是订单分析应用服务。
|
||||
analytics *analyticsService
|
||||
}
|
||||
@@ -73,8 +75,9 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
|
||||
accountProfile: accountProfile,
|
||||
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
|
||||
chat: chatapp.New(newStoreChatApplicationRepository(server.Store)),
|
||||
chat: newChatSendingApplication(server),
|
||||
uncertainNotifications: notificationsapp.New(newStoreNotificationUncertainRepository(server.Store)),
|
||||
notificationChannels: notificationsapp.NewChannelService(newStoreNotificationChannelRepository(server.Store), server.notifier),
|
||||
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,27 +281,27 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
|
||||
return
|
||||
}
|
||||
// session 保存会话,供当前处理流程使用
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: chatID, BuyerID: buyerID,
|
||||
// session 保存已完成账号归属校验的应用层会话摘要。
|
||||
session := chatapp.Session{AccountID: accountID, ChatID: chatID, BuyerID: buyerID,
|
||||
BuyerName: r.FormValue("buyer_name"), BuyerAvatar: r.FormValue("buyer_avatar_url"),
|
||||
ItemID: r.FormValue("item_id"), ItemTitle: r.FormValue("item_title")}
|
||||
// sent、err 保存sent、err,供当前处理流程使用
|
||||
sent, err := s.communicationApplication().SendChatImage(r.Context(), chatImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
|
||||
sent, err := s.chatApplication().SendImage(r.Context(), chatapp.ImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
|
||||
if err != nil {
|
||||
if errors.Is(err, errCommunicationUnavailable) {
|
||||
if errors.Is(err, chatapp.ErrUnavailable) {
|
||||
writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用")
|
||||
} else if errors.Is(err, errChatOffline) {
|
||||
} else if errors.Is(err, chatapp.ErrOffline) {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片")
|
||||
} else if errors.Is(err, errChatSend) {
|
||||
} else if errors.Is(err, chatapp.ErrSend) {
|
||||
writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": sent})
|
||||
} else if errors.Is(err, errChatStatusSave) {
|
||||
} else if errors.Is(err, chatapp.ErrStatusSave) {
|
||||
writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败")
|
||||
} else {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送图片失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
|
||||
}
|
||||
|
||||
// listChatMessages 负责list聊天消息列表相关处理。
|
||||
@@ -447,23 +447,23 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符")
|
||||
return
|
||||
}
|
||||
// sent、err 保存sent、err,供当前处理流程使用
|
||||
sent, err := s.communicationApplication().SendChatText(r.Context(), chatTextInput{Session: db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID, BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, Text: input.Text})
|
||||
// sent、err 保存应用层发送结果及错误;应用层返回的消息不含凭证。
|
||||
sent, err := s.chatApplication().SendText(r.Context(), chatapp.OutgoingInput{Session: chatapp.Session{AccountID: input.AccountID, ChatID: input.ChatID, BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, Text: input.Text})
|
||||
if err != nil {
|
||||
if errors.Is(err, errCommunicationUnavailable) {
|
||||
if errors.Is(err, chatapp.ErrUnavailable) {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
} else if errors.Is(err, errChatOffline) {
|
||||
} else if errors.Is(err, chatapp.ErrOffline) {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息")
|
||||
} else if errors.Is(err, errChatSend) {
|
||||
} else if errors.Is(err, chatapp.ErrSend) {
|
||||
writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": sent})
|
||||
} else if errors.Is(err, errChatStatusSave) {
|
||||
} else if errors.Is(err, chatapp.ErrStatusSave) {
|
||||
writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败")
|
||||
} else {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送消息失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
|
||||
}
|
||||
|
||||
// markChatRead 负责mark聊天Read相关处理。
|
||||
|
||||
@@ -3,10 +3,12 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/automation"
|
||||
domainchat "xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -15,12 +17,6 @@ import (
|
||||
var (
|
||||
// errCommunicationUnavailable 表示聊天或自动化依赖尚未初始化。
|
||||
errCommunicationUnavailable = errors.New("通信服务未启用")
|
||||
// errChatOffline 表示目标账号当前没有在线运行实例。
|
||||
errChatOffline = errors.New("账号当前离线")
|
||||
// errChatSend 表示远端聊天消息发送失败。
|
||||
errChatSend = errors.New("聊天消息发送失败")
|
||||
// errChatStatusSave 表示远端消息已发送但本地状态保存失败。
|
||||
errChatStatusSave = errors.New("聊天发送状态保存失败")
|
||||
)
|
||||
|
||||
// communicationService 是聊天、账号任务和通知应用服务。
|
||||
@@ -39,26 +35,6 @@ type accountTaskUpdateInput struct {
|
||||
Settings db.AccountTaskSettings
|
||||
}
|
||||
|
||||
// chatTextInput 是发送文字消息的业务输入。
|
||||
type chatTextInput struct {
|
||||
// Session 是聊天会话及买家信息。
|
||||
Session db.ChatSession
|
||||
// Text 是待发送的文字内容。
|
||||
Text string
|
||||
}
|
||||
|
||||
// chatImageInput 是发送图片消息的业务输入。
|
||||
type chatImageInput struct {
|
||||
// Session 是聊天会话及买家信息。
|
||||
Session db.ChatSession
|
||||
// Filename 是上传图片文件名。
|
||||
Filename string
|
||||
// ContentType 是图片 MIME 类型。
|
||||
ContentType string
|
||||
// Data 是图片二进制内容。
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// notificationBindingRow 是通知绑定列表的一行业务数据。
|
||||
type notificationBindingRow struct {
|
||||
// ID 是绑定记录标识。
|
||||
@@ -213,91 +189,193 @@ func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.C
|
||||
return svc.repository.DeleteAccountNotificationBindings(ctx, userID, cookieID)
|
||||
}
|
||||
|
||||
// SendChatText 创建并发送一条文字消息,失败时保留可重试的本地失败状态。
|
||||
func (svc *communicationService) SendChatText(ctx context.Context, input chatTextInput) (*db.ChatMessage, error) {
|
||||
// s 是当前通信应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
return nil, errCommunicationUnavailable
|
||||
}
|
||||
// sender 保存目标账号的在线发送句柄。
|
||||
sender, ok := s.Manager.GetInstance(input.Session.CookieID)
|
||||
if !ok || sender == nil {
|
||||
return nil, errChatOffline
|
||||
}
|
||||
// message 和 err 保存待发送消息落库结果。
|
||||
message, err := s.chat.CreateOutgoing(ctx, input.Session, input.Text)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("保存待发送消息失败: %w", err)
|
||||
}
|
||||
// err 表示文字发送错误。
|
||||
if err := sender.SendText(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, input.Text); err != nil {
|
||||
// failed 保存发送失败后的本地消息状态。
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed")
|
||||
return failed, fmt.Errorf("%w: %v", errChatSend, err)
|
||||
}
|
||||
// sent 和 err 保存远端发送成功后的本地状态。
|
||||
sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
return sent, fmt.Errorf("%w: %v", errChatStatusSave, err)
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// SendChatImage 上传并发送一条图片消息,失败时保留可重试的本地失败状态。
|
||||
func (svc *communicationService) SendChatImage(ctx context.Context, input chatImageInput) (*db.ChatMessage, error) {
|
||||
// s 是当前通信应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
return nil, errCommunicationUnavailable
|
||||
}
|
||||
// sender 和 ok 保存目标账号的在线发送句柄及存在性。
|
||||
sender, ok := s.Manager.GetInstance(input.Session.CookieID)
|
||||
if !ok || sender == nil {
|
||||
return nil, errChatOffline
|
||||
}
|
||||
// cookies 和 err 保存图片上传使用的账号凭证。
|
||||
cookies, err := svc.repository.GetCookieValue(ctx, input.Session.CookieID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取账号凭证失败: %w", err)
|
||||
}
|
||||
// uploader 和 ok 表示图片上传客户端及其能力支持情况。
|
||||
uploader, ok := s.mtopClient().(interface {
|
||||
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errCommunicationUnavailable
|
||||
}
|
||||
// upload 和 err 保存图片上传结果。
|
||||
upload, err := uploader.UploadChatImage(ctx, cookies, input.Filename, input.ContentType, input.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", errChatSend, err)
|
||||
}
|
||||
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies {
|
||||
// err 表示保存图片上传后刷新 Cookie 的错误,仅忽略并继续发送。
|
||||
_ = svc.repository.UpdateCookieValue(ctx, input.Session.CookieID, upload.UpdatedCookies)
|
||||
sender.UpdateCookie(upload.UpdatedCookies)
|
||||
}
|
||||
// message 和 err 保存图片消息落库结果。
|
||||
message, err := s.chat.CreateOutgoingMedia(ctx, input.Session, "image", upload.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("保存待发送图片失败: %w", err)
|
||||
}
|
||||
// err 表示图片发送错误。
|
||||
if err := sender.SendImage(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, upload.URL, 0); err != nil {
|
||||
// failed 保存图片发送失败后的本地消息状态。
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed")
|
||||
return failed, fmt.Errorf("%w: %v", errChatSend, err)
|
||||
}
|
||||
// sent 和 err 保存图片发送成功后的本地状态。
|
||||
sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
return sent, fmt.Errorf("%w: %v", errChatStatusSave, err)
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// MarkChatRead 将指定聊天会话标记为已读。
|
||||
func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error {
|
||||
return svc.repository.MarkChatRead(ctx, userID, accountID, chatID)
|
||||
}
|
||||
|
||||
// storeChatOutgoingRepository 将领域聊天服务适配为实时发送应用端口。
|
||||
type storeChatOutgoingRepository struct {
|
||||
// service 保存聊天消息幂等写入和实时事件发布能力。
|
||||
service *domainchat.Service
|
||||
}
|
||||
|
||||
// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。
|
||||
func (r storeChatOutgoingRepository) CreateOutgoing(ctx context.Context, session chatapp.Session, text string) (chatapp.Message, error) {
|
||||
if r.service == nil {
|
||||
return chatapp.Message{}, chatapp.ErrUnavailable
|
||||
}
|
||||
// message、err 保存领域服务返回的消息及写入错误。
|
||||
message, err := r.service.CreateOutgoing(ctx, dbChatSessionFromApplication(session), text)
|
||||
return applicationChatMessage(message), err
|
||||
}
|
||||
|
||||
// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。
|
||||
func (r storeChatOutgoingRepository) CreateOutgoingMedia(ctx context.Context, session chatapp.Session, messageType, content string) (chatapp.Message, error) {
|
||||
if r.service == nil {
|
||||
return chatapp.Message{}, chatapp.ErrUnavailable
|
||||
}
|
||||
// message、err 保存领域服务返回的媒体消息及写入错误。
|
||||
message, err := r.service.CreateOutgoingMedia(ctx, dbChatSessionFromApplication(session), messageType, content)
|
||||
return applicationChatMessage(message), err
|
||||
}
|
||||
|
||||
// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。
|
||||
func (r storeChatOutgoingRepository) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (chatapp.Message, error) {
|
||||
if r.service == nil {
|
||||
return chatapp.Message{}, chatapp.ErrUnavailable
|
||||
}
|
||||
// message、err 保存领域服务返回的状态消息及更新错误。
|
||||
message, err := r.service.SetOutgoingStatus(ctx, accountID, key, status)
|
||||
return applicationChatMessage(message), err
|
||||
}
|
||||
|
||||
// managerChatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。
|
||||
type managerChatSenderProvider struct {
|
||||
// manager 保存当前进程内的账号运行时管理器。
|
||||
manager *account.Manager
|
||||
}
|
||||
|
||||
// Sender 返回指定账号的在线发送能力。
|
||||
func (p managerChatSenderProvider) Sender(accountID string) (chatapp.Sender, bool) {
|
||||
if p.manager == nil {
|
||||
return nil, false
|
||||
}
|
||||
// sender、ok 保存账号管理器返回的运行时发送器及存在性。
|
||||
sender, ok := p.manager.GetInstance(accountID)
|
||||
if !ok || sender == nil {
|
||||
return nil, false
|
||||
}
|
||||
return managerChatSender{sender: sender}, true
|
||||
}
|
||||
|
||||
// managerChatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。
|
||||
type managerChatSender struct {
|
||||
// sender 保存账号运行时提供的最小消息发送能力。
|
||||
sender automation.MessageSender
|
||||
}
|
||||
|
||||
// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。
|
||||
func (s managerChatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error {
|
||||
return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// SendImage 发送图片并将应用层幂等键传递给运行时接口。
|
||||
func (s managerChatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error {
|
||||
return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID)
|
||||
}
|
||||
|
||||
// storeChatCredentialRepository 将账号 Cookie 仓储适配为图片发送端口。
|
||||
type storeChatCredentialRepository struct {
|
||||
// store 保存数据库聚合入口,仅在凭证适配器内读取和更新 Cookie。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// GetCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。
|
||||
func (r storeChatCredentialRepository) GetCookieValue(ctx context.Context, accountID string) (string, error) {
|
||||
if r.store == nil || r.store.Cookies == nil {
|
||||
return "", chatapp.ErrUnavailable
|
||||
}
|
||||
return r.store.Cookies.GetValue(ctx, accountID)
|
||||
}
|
||||
|
||||
// UpdateCookieValue 保存图片上传后平台刷新的账号凭证。
|
||||
func (r storeChatCredentialRepository) UpdateCookieValue(ctx context.Context, accountID, cookieValue string) error {
|
||||
if r.store == nil || r.store.Cookies == nil {
|
||||
return chatapp.ErrUnavailable
|
||||
}
|
||||
return r.store.Cookies.UpdateValueExisting(ctx, accountID, cookieValue)
|
||||
}
|
||||
|
||||
// serverChatImageUploader 将 Server 当前 MTOP 客户端适配为图片上传端口。
|
||||
type serverChatImageUploader struct {
|
||||
// server 提供可动态替换的 MTOP 客户端,便于测试注入平台替身。
|
||||
server *Server
|
||||
// credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。
|
||||
credentials storeChatCredentialRepository
|
||||
// manager 负责将刷新后的凭证同步到在线运行时。
|
||||
manager *account.Manager
|
||||
}
|
||||
|
||||
// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。
|
||||
func (u serverChatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) {
|
||||
if u.server == nil {
|
||||
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
|
||||
}
|
||||
// cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。
|
||||
cookieValue, err := u.credentials.GetCookieValue(ctx, accountID)
|
||||
if err != nil {
|
||||
return chatapp.ImageUpload{}, err
|
||||
}
|
||||
// uploader、ok 保存 MTOP 图片上传能力及接口支持情况。
|
||||
uploader, ok := u.server.mtopClient().(interface {
|
||||
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
|
||||
})
|
||||
if !ok {
|
||||
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
|
||||
}
|
||||
// upload、err 保存图片平台返回结果及调用错误。
|
||||
upload, err := uploader.UploadChatImage(ctx, cookieValue, filename, contentType, data)
|
||||
if err != nil {
|
||||
return chatapp.ImageUpload{}, err
|
||||
}
|
||||
if upload == nil {
|
||||
return chatapp.ImageUpload{}, chatapp.ErrSend
|
||||
}
|
||||
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookieValue {
|
||||
// persistErr 保存刷新凭证的持久化错误;该错误必须反馈给调用方,避免静默丢失会话状态。
|
||||
if persistErr := u.credentials.UpdateCookieValue(ctx, accountID, upload.UpdatedCookies); persistErr != nil {
|
||||
return chatapp.ImageUpload{}, persistErr
|
||||
}
|
||||
if u.manager != nil {
|
||||
// sender、senderOK 保存刷新凭证同步到运行时的结果。
|
||||
sender, senderOK := u.manager.GetInstance(accountID)
|
||||
if senderOK && sender != nil {
|
||||
sender.UpdateCookie(upload.UpdatedCookies)
|
||||
}
|
||||
}
|
||||
}
|
||||
return chatapp.ImageUpload{URL: upload.URL}, nil
|
||||
}
|
||||
|
||||
// newChatSendingApplication 创建实时聊天发送应用服务及其 Server 适配器。
|
||||
func newChatSendingApplication(server *Server) *chatapp.Service {
|
||||
// domainService 保存聊天领域服务;空值表示发送能力未装配。
|
||||
var domainService *domainchat.Service
|
||||
if server != nil {
|
||||
domainService = server.chat
|
||||
}
|
||||
// store 保存聊天适配器可用的数据库入口;空 Server 仍返回可安全调用的不可用服务。
|
||||
var store *db.Store
|
||||
// manager 保存账号运行时管理器;空值表示无法发送平台消息。
|
||||
var manager *account.Manager
|
||||
if server != nil {
|
||||
store, manager = server.Store, server.Manager
|
||||
}
|
||||
return chatapp.NewWithSending(
|
||||
newStoreChatApplicationRepository(store),
|
||||
storeChatOutgoingRepository{service: domainService},
|
||||
managerChatSenderProvider{manager: manager},
|
||||
serverChatImageUploader{server: server, credentials: storeChatCredentialRepository{store: store}, manager: manager},
|
||||
)
|
||||
}
|
||||
|
||||
// applicationChatMessage 将数据库消息转换为应用层模型;空指针保持零值。
|
||||
func applicationChatMessage(message *db.ChatMessage) chatapp.Message {
|
||||
if message == nil {
|
||||
return chatapp.Message{}
|
||||
}
|
||||
return chatapp.Message{
|
||||
ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, MessageKey: message.MessageKey,
|
||||
Direction: message.Direction, SenderID: message.SenderID, SenderName: message.SenderName,
|
||||
MessageType: message.MessageType, Content: message.Content, Status: message.Status, SentAt: message.SentAt,
|
||||
}
|
||||
}
|
||||
|
||||
// 确保各 Server 适配器覆盖聊天应用服务定义的最小端口。
|
||||
var (
|
||||
_ chatapp.OutgoingRepository = storeChatOutgoingRepository{}
|
||||
_ chatapp.SenderProvider = managerChatSenderProvider{}
|
||||
_ chatapp.Sender = managerChatSender{}
|
||||
_ chatapp.ImageUploader = serverChatImageUploader{}
|
||||
)
|
||||
@@ -554,6 +554,16 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, accountMutationResponse{Success: true, ID: req.ID})
|
||||
}
|
||||
|
||||
// updateCookieRequest 是更新账号 Cookie 的 HTTP 请求 DTO;last_refresh_at 用于兼容客户端的并发覆盖检测。
|
||||
type updateCookieRequest struct {
|
||||
// Value 是本次请求携带的明文 Cookie;只在 Server 请求作用域内传递。
|
||||
Value string `json:"value"`
|
||||
// LoginMethod 是可选登录方式,用于成功审计和账号启用语义。
|
||||
LoginMethod string `json:"login_method"`
|
||||
// LastRefreshAt 是客户端读取到的最近凭证刷新时间;零值表示旧客户端不启用冲突检查。
|
||||
LastRefreshAt int64 `json:"last_refresh_at"`
|
||||
}
|
||||
|
||||
// updateCookie 更新 cookie 值。
|
||||
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 保存cid,供当前处理流程使用
|
||||
@@ -563,11 +573,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
Value string `json:"value"`
|
||||
LoginMethod string `json:"login_method"`
|
||||
}
|
||||
// req 保存请求中的 Cookie、登录方式和可选凭证版本。
|
||||
var req updateCookieRequest
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -576,7 +583,11 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
|
||||
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod, ExpectedRevision: req.LastRefreshAt}); err != nil {
|
||||
if errors.Is(err, accountapp.ErrCredentialConflict) {
|
||||
writeErr(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
@@ -534,6 +535,55 @@ func TestUpdateCookie(t *testing.T) {
|
||||
requireCookieSnapshotCleared(t, store, "acc1")
|
||||
}
|
||||
|
||||
// TestUpdateCookieRejectsStaleRevision 验证客户端携带过期凭证版本时不会覆盖较新的 Cookie。
|
||||
func TestUpdateCookieRejectsStaleRevision(t *testing.T) {
|
||||
// srv、store、cleanup 保存测试服务器、数据库和资源释放函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// ctx 保存本次测试使用的数据库上下文。
|
||||
ctx := context.Background()
|
||||
// baselineValue 保存建立可比较版本所需的旧 Cookie 值。
|
||||
baselineValue := "unb=baseline; _m_h5_tk=baseline_token;"
|
||||
// baselineErr 表示写入可比较版本基线时的数据库错误。
|
||||
if baselineErr := store.Cookies.UpdateRenewalCookie(ctx, "acc1", baselineValue, `{}`, 100); baselineErr != nil {
|
||||
t.Fatalf("写入基线 Cookie 失败: %v", baselineErr)
|
||||
}
|
||||
// initialErr 保存读取初始账号详情时的错误。
|
||||
initial, initialErr := store.Cookies.GetDetails(ctx, "acc1")
|
||||
if initialErr != nil {
|
||||
t.Fatalf("读取初始账号详情失败: %v", initialErr)
|
||||
}
|
||||
// newerValue 是并发请求已经写入的新 Cookie 值。
|
||||
newerValue := "unb=latest; _m_h5_tk=latest_token;"
|
||||
// updateErr 表示写入并发新 Cookie 时的数据库错误。
|
||||
if updateErr := store.Cookies.UpdateRenewalCookie(ctx, "acc1", newerValue, initial.MetadataJSON, 200); updateErr != nil {
|
||||
t.Fatalf("写入并发新 Cookie 失败: %v", updateErr)
|
||||
}
|
||||
// h 保存 HTTP 路由;session 保存当前用户的会话 Cookie。
|
||||
h := srv.Router()
|
||||
// session 保存当前用户登录后的 HttpOnly 会话 Cookie。
|
||||
session := loginHelper(t, h)
|
||||
// body 保存携带旧版本的更新请求体。
|
||||
body := fmt.Sprintf(`{"value":"unb=stale; _m_h5_tk=stale_token;","last_refresh_at":%d}`, initial.LastRefreshAt)
|
||||
// req、rec 保存 HTTP 请求与响应记录器。
|
||||
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
|
||||
req.AddCookie(session)
|
||||
// rec 记录过期版本请求的 HTTP 响应,供状态码与错误契约断言。
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("过期版本应返回 409,got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// latest、latestErr 保存冲突后数据库中的凭证值和读取错误。
|
||||
latest, latestErr := store.Cookies.GetDetails(ctx, "acc1")
|
||||
if latestErr != nil {
|
||||
t.Fatalf("读取冲突后账号详情失败: %v", latestErr)
|
||||
}
|
||||
if latest.Value != newerValue {
|
||||
t.Fatalf("过期版本覆盖了新 Cookie: %q", latest.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager 负责TestUpdateRunning登录凭证WakesCredentialBlocked自动化WithoutManager相关处理。
|
||||
func TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager(t *testing.T) {
|
||||
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
|
||||
|
||||
@@ -13,6 +13,176 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// notificationChannelCreateRequest 是创建通知渠道的具名 HTTP 请求 DTO;Config 只写入应用端口。
|
||||
type notificationChannelCreateRequest struct {
|
||||
// Name 是渠道名称。
|
||||
Name string `json:"name"`
|
||||
// Type 是渠道协议类型。
|
||||
Type string `json:"type"`
|
||||
// Config 是渠道敏感配置 JSON,禁止进入响应或日志。
|
||||
Config string `json:"config"`
|
||||
// EventTypes 是渠道订阅事件类型编码。
|
||||
EventTypes string `json:"event_types"`
|
||||
// Enabled 表示渠道是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// notificationChannelPatchRequest 是更新通知渠道的具名部分更新 DTO。
|
||||
type notificationChannelPatchRequest struct {
|
||||
// Name 是可选的新渠道名称。
|
||||
Name *string `json:"name"`
|
||||
// Type 是可选的新渠道协议类型。
|
||||
Type *string `json:"type"`
|
||||
// Config 是可选的新敏感配置 JSON,禁止进入响应或日志。
|
||||
Config *string `json:"config"`
|
||||
// EventTypes 是可选的新订阅事件类型编码。
|
||||
EventTypes *string `json:"event_types"`
|
||||
// Enabled 是可选的新启用状态。
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// notificationBindingRequest 是账号通知绑定更新的具名 HTTP 请求 DTO。
|
||||
type notificationBindingRequest struct {
|
||||
// ChannelIDs 是覆盖式保存的渠道 ID 列表。
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
// ChannelID 是单条绑定更新的渠道 ID。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// Enabled 是单条绑定是否启用;省略时默认为启用。
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// storeNotificationChannelRepository 将通知数据库能力适配为通知应用端口。
|
||||
type storeNotificationChannelRepository struct {
|
||||
// store 保存数据库聚合入口,仅在 Server 基础设施适配器内使用。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// ListChannels 查询渠道摘要并丢弃配置,避免敏感配置进入应用展示模型。
|
||||
func (r storeNotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) {
|
||||
// rows、err 保存数据库渠道读取结果;Config 仅在适配器内部被解密读取。
|
||||
rows, err := r.store.Notifications.AllChannelsForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// summaries 保存不含渠道配置的应用摘要。
|
||||
summaries := make([]notificationsapp.ChannelSummary, 0, len(rows))
|
||||
// row 表示当前待转换的数据库渠道行。
|
||||
for _, row := range rows {
|
||||
summaries = append(summaries, notificationsapp.ChannelSummary{ID: row.ID, Name: row.Name, Type: row.Type, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID})
|
||||
}
|
||||
return summaries, nil
|
||||
}
|
||||
|
||||
// GetChannelForUpdate 查询归属渠道的完整记录,仅供应用层合并部分更新。
|
||||
func (r storeNotificationChannelRepository) GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*notificationsapp.ChannelRecord, error) {
|
||||
// row、err 保存带用户归属的数据库渠道记录。
|
||||
row, err := r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if row == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return ¬ificationsapp.ChannelRecord{ID: row.ID, Name: row.Name, Type: row.Type, Config: row.Config, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}, nil
|
||||
}
|
||||
|
||||
// CreateChannel 将应用输入转换为数据库行并创建渠道。
|
||||
func (r storeNotificationChannelRepository) CreateChannel(ctx context.Context, userID int64, input notificationsapp.ChannelInput) (int64, error) {
|
||||
// row 保存待加密写入数据库的渠道行;Config 不向 HTTP 返回。
|
||||
row := db.NotificationChannelRow{Name: input.Name, Type: input.Type, Config: input.Config, EventTypes: input.EventTypes, Enabled: input.Enabled, UserID: userID}
|
||||
return r.store.Notifications.CreateChannel(ctx, &row)
|
||||
}
|
||||
|
||||
// UpdateChannel 将应用层完整渠道记录转换为数据库更新。
|
||||
func (r storeNotificationChannelRepository) UpdateChannel(ctx context.Context, userID int64, record notificationsapp.ChannelRecord) error {
|
||||
// row 保存待加密写入数据库的渠道行;调用方已完成归属和字段校验。
|
||||
row := db.NotificationChannelRow{ID: record.ID, Name: record.Name, Type: record.Type, Config: record.Config, EventTypes: record.EventTypes, Enabled: record.Enabled, UserID: userID}
|
||||
return r.store.Notifications.UpdateChannelForUser(ctx, &row, userID)
|
||||
}
|
||||
|
||||
// DeleteChannel 删除用户拥有的渠道并统一转换不存在错误。
|
||||
func (r storeNotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error {
|
||||
return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID))
|
||||
}
|
||||
|
||||
// OwnsChannel 查询通知渠道归属,不读取配置内容。
|
||||
func (r storeNotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) {
|
||||
return r.store.Notifications.OwnsChannel(ctx, channelID, userID)
|
||||
}
|
||||
|
||||
// OwnsAccount 查询账号归属,不读取或解密 Cookie。
|
||||
func (r storeNotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) {
|
||||
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
|
||||
}
|
||||
|
||||
// ListBindings 查询绑定摘要并转换为应用模型。
|
||||
func (r storeNotificationChannelRepository) ListBindings(ctx context.Context, userID int64) ([]notificationsapp.BindingSummary, error) {
|
||||
// rows、err 保存数据库绑定摘要及错误。
|
||||
rows, err := r.store.Notifications.ListBindingsForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// bindings 保存不含配置的应用绑定摘要。
|
||||
bindings := make([]notificationsapp.BindingSummary, 0, len(rows))
|
||||
// row 表示当前待转换的数据库绑定行。
|
||||
for _, row := range rows {
|
||||
bindings = append(bindings, notificationsapp.BindingSummary{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled})
|
||||
}
|
||||
return bindings, nil
|
||||
}
|
||||
|
||||
// GetBindingIDs 查询账号启用的通知渠道 ID。
|
||||
func (r storeNotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
|
||||
return r.store.Notifications.AccountBindings(ctx, cookieID)
|
||||
}
|
||||
|
||||
// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。
|
||||
func (r storeNotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
|
||||
return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs))
|
||||
}
|
||||
|
||||
// SetSingleBinding 更新单个账号绑定状态。
|
||||
func (r storeNotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
|
||||
return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled)
|
||||
}
|
||||
|
||||
// DeleteBinding 删除用户的一条绑定。
|
||||
func (r storeNotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
|
||||
return r.store.Notifications.DeleteBinding(ctx, userID, bindingID)
|
||||
}
|
||||
|
||||
// DeleteAccountBindings 删除用户账号的全部绑定。
|
||||
func (r storeNotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
|
||||
return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)
|
||||
}
|
||||
|
||||
// normalizeNotificationRepositoryError 将数据库归属错误转换为应用错误,隐藏基础设施类型。
|
||||
func normalizeNotificationRepositoryError(err error) error {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return notificationsapp.ErrChannelNotFound
|
||||
}
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
return notificationsapp.ErrChannelForbidden
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// newStoreNotificationChannelRepository 构造通知渠道应用端口适配器。
|
||||
func newStoreNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository {
|
||||
if store == nil || store.Notifications == nil || store.Cookies == nil {
|
||||
return nil
|
||||
}
|
||||
return storeNotificationChannelRepository{store: store}
|
||||
}
|
||||
|
||||
// notificationChannelsApplication 返回当前 Server 绑定的通知渠道应用服务。
|
||||
func (s *Server) notificationChannelsApplication() *notificationsapp.ChannelService {
|
||||
return s.applicationServiceSet().notificationChannels
|
||||
}
|
||||
|
||||
// ensureStoreNotificationChannelRepository 保证通知渠道应用端口覆盖全部能力。
|
||||
var _ notificationsapp.ChannelRepository = storeNotificationChannelRepository{}
|
||||
|
||||
// storeNotificationUncertainRepository 将数据库通知摘要查询适配为应用层端口。
|
||||
type storeNotificationUncertainRepository struct {
|
||||
// store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。
|
||||
@@ -124,10 +294,10 @@ func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.
|
||||
|
||||
// listChannels 负责list渠道列表相关处理。
|
||||
func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// chs、err 保存chs、err,供当前处理流程使用
|
||||
chs, err := s.communicationApplication().ListNotificationChannels(r.Context(), sess.UserID)
|
||||
// chs、err 保存通知渠道非敏感摘要及查询错误。
|
||||
chs, err := s.notificationChannelsApplication().ListChannels(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -137,24 +307,18 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// createChannel 负责create渠道相关处理。
|
||||
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Config string `json:"config"`
|
||||
EventTypes string `json:"event_types"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
// req 保存具名通知渠道创建请求;Config 只写入应用端口。
|
||||
var req notificationChannelCreateRequest
|
||||
if // err 保存 JSON 解码错误。
|
||||
err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
// id、err 保存id、err,供当前处理流程使用
|
||||
id, err := s.communicationApplication().CreateNotificationChannel(r.Context(), db.NotificationChannelRow{
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled, UserID: sess.UserID,
|
||||
// id、err 保存渠道创建结果及应用错误。
|
||||
id, err := s.notificationChannelsApplication().CreateChannel(r.Context(), sess.UserID, notificationsapp.ChannelInput{
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
@@ -165,59 +329,30 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// updateChannel 负责update渠道相关处理。
|
||||
func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
|
||||
// id、err 保存id、err,供当前处理流程使用
|
||||
// id、err 保存路径中的渠道 ID 及解析错误。
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Type *string `json:"type"`
|
||||
Config *string `json:"config"`
|
||||
EventTypes *string `json:"event_types"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
// req 保存具名通知渠道部分更新请求;Config 不会进入响应。
|
||||
var req notificationChannelPatchRequest
|
||||
if // err 保存 JSON 解码错误。
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// row、err 保存row、err,供当前处理流程使用
|
||||
row, err := s.communicationApplication().GetNotificationChannel(r.Context(), id, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
if row == nil {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
if req.Name != nil {
|
||||
row.Name = *req.Name
|
||||
}
|
||||
if req.Type != nil {
|
||||
row.Type = *req.Type
|
||||
}
|
||||
if req.Config != nil {
|
||||
row.Config = *req.Config
|
||||
}
|
||||
if req.EventTypes != nil {
|
||||
row.EventTypes = *req.EventTypes
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
row.Enabled = *req.Enabled
|
||||
}
|
||||
if row.Name == "" || row.Type == "" {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().UpdateNotificationChannel(r.Context(), *row, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
// err 保存应用层部分更新结果。
|
||||
if err := s.notificationChannelsApplication().UpdateChannel(r.Context(), sess.UserID, id, notificationsapp.ChannelPatch{
|
||||
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled,
|
||||
}); err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrChannelInvalidInput) {
|
||||
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
@@ -229,17 +364,17 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// deleteChannel 负责delete渠道相关处理。
|
||||
func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
// id、err 保存id、err,供当前处理流程使用
|
||||
// id、err 保存路径中的渠道 ID 及解析错误。
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().DeleteNotificationChannel(r.Context(), id, sess.UserID); err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
// err 保存应用层删除结果。
|
||||
if err := s.notificationChannelsApplication().DeleteChannel(r.Context(), sess.UserID, id); err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
@@ -251,28 +386,27 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// testChannel 向指定渠道发送一条测试通知,便于用户验证配置是否正确。
|
||||
func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
// id、err 保存id、err,供当前处理流程使用
|
||||
// id、err 保存路径中的渠道 ID 及解析错误。
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
// notifier 表示当前 Server 是否装配了实际通知发送器;未装配时保持旧接口的 503 语义,避免先执行归属查询。
|
||||
if s.notifier == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
|
||||
return
|
||||
}
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
// body 保存请求体,供当前处理流程使用
|
||||
body := "🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
|
||||
time.Now().Format("2006-01-02 15:04:05")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().TestNotificationChannel(r.Context(), id, authSess(r).UserID, body); err != nil {
|
||||
if errors.Is(err, errCommunicationUnavailable) {
|
||||
// err 保存应用层测试发送结果。
|
||||
if err := s.notificationChannelsApplication().TestChannel(r.Context(), authSess(r).UserID, id, time.Now()); err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrNotifierUnavailable) {
|
||||
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -281,14 +415,17 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// getAccountBindings 负责get账号Bindings相关处理。
|
||||
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 保存cid,供当前处理流程使用
|
||||
// cid 保存路径中的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
return
|
||||
}
|
||||
// ids、err 保存ids、err,供当前处理流程使用
|
||||
ids, err := s.communicationApplication().GetNotificationBindingIDs(r.Context(), cid)
|
||||
// sess 保存当前认证用户,用于应用层账号归属校验。
|
||||
sess := authSess(r)
|
||||
// ids、err 保存账号启用渠道 ID 及查询错误。
|
||||
ids, err := s.notificationChannelsApplication().GetBindingIDs(r.Context(), sess.UserID, cid)
|
||||
if err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrAccountForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
@@ -297,10 +434,10 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// listMessageNotifications 负责list消息通知列表相关处理。
|
||||
func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// rows、err 保存rows、err,供当前处理流程使用
|
||||
rows, err := s.communicationApplication().ListNotificationBindings(r.Context(), sess.UserID)
|
||||
// rows、err 保存通知绑定摘要及查询错误。
|
||||
rows, err := s.notificationChannelsApplication().ListBindings(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -308,59 +445,57 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
|
||||
// out 保存out,供当前处理流程使用
|
||||
out := make(notificationBindingListResponse, len(rows))
|
||||
// cookieID、bindings 表示当前遍历过程中的登录凭证ID、bindings
|
||||
for cookieID, bindings := range rows {
|
||||
// binding 表示当前遍历过程中的binding
|
||||
for _, binding := range bindings {
|
||||
out[cookieID] = append(out[cookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled})
|
||||
}
|
||||
// binding 表示当前遍历到的通知绑定摘要。
|
||||
for _, binding := range rows {
|
||||
out[binding.CookieID] = append(out[binding.CookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// setAccountBindings 负责set账号Bindings相关处理。
|
||||
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 保存cid,供当前处理流程使用
|
||||
// cid 保存路径中的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
return
|
||||
}
|
||||
// req 保存req,供当前处理流程使用
|
||||
var req struct {
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
// req 保存具名账号通知绑定请求。
|
||||
var req notificationBindingRequest
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if req.ChannelID != 0 {
|
||||
if !s.requireChannelOwner(w, r, req.ChannelID) {
|
||||
return
|
||||
}
|
||||
// enabled 保存启用状态,供当前处理流程使用
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
// err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().SetSingleNotificationBinding(r.Context(), cid, req.ChannelID, enabled)
|
||||
// err 保存单条绑定应用用例结果。
|
||||
err := s.notificationChannelsApplication().SetSingleBinding(r.Context(), authSess(r).UserID, cid, req.ChannelID, enabled)
|
||||
if err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrAccountForbidden) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
return
|
||||
}
|
||||
// channelID 表示当前遍历过程中的渠道ID
|
||||
for _, channelID := range req.ChannelIDs {
|
||||
if !s.requireChannelOwner(w, r, channelID) {
|
||||
// err 保存批量绑定应用用例结果。
|
||||
if err := s.notificationChannelsApplication().SetBindings(r.Context(), authSess(r).UserID, cid, req.ChannelIDs); err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrAccountForbidden) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return
|
||||
}
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().SetNotificationBindings(r.Context(), cid, req.ChannelIDs); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
@@ -369,15 +504,16 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// deleteMessageNotification 负责delete消息通知相关处理。
|
||||
func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// id、err 保存id、err,供当前处理流程使用
|
||||
// id、err 保存路径中的绑定 ID 及解析错误。
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "notification_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效ID")
|
||||
return
|
||||
}
|
||||
err = s.communicationApplication().DeleteNotificationBinding(r.Context(), sess.UserID, id)
|
||||
// err 保存应用层绑定删除结果。
|
||||
err = s.notificationChannelsApplication().DeleteBinding(r.Context(), sess.UserID, id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
@@ -387,13 +523,17 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques
|
||||
|
||||
// deleteAccountNotifications 负责delete账号通知列表相关处理。
|
||||
func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
sess := authSess(r)
|
||||
// cid 保存cid,供当前处理流程使用
|
||||
// cid 保存路径中的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
// err 保存err,供当前处理流程使用
|
||||
err := s.communicationApplication().DeleteAccountNotificationBindings(r.Context(), sess.UserID, cid)
|
||||
// err 保存应用层账号绑定删除结果。
|
||||
err := s.notificationChannelsApplication().DeleteAccountBindings(r.Context(), sess.UserID, cid)
|
||||
if err != nil {
|
||||
if errors.Is(err, notificationsapp.ErrAccountForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -144,6 +144,20 @@ func newChatMessageDTOFromPointer(message *db.ChatMessage) chatMessageDTO {
|
||||
return newChatMessageDTO(*message)
|
||||
}
|
||||
|
||||
// newChatMessageDTOFromApplication 将聊天应用层发送结果转换为 HTTP DTO,避免响应引用数据库模型。
|
||||
func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO {
|
||||
if message == nil {
|
||||
return chatMessageDTO{}
|
||||
}
|
||||
return chatMessageDTO{
|
||||
ID: message.ID, AccountID: message.AccountID, ChatID: message.ChatID,
|
||||
MessageKey: message.MessageKey, Direction: message.Direction,
|
||||
SenderID: message.SenderID, SenderName: message.SenderName,
|
||||
MessageType: message.MessageType, Content: message.Content,
|
||||
Status: message.Status, SentAt: message.SentAt,
|
||||
}
|
||||
}
|
||||
|
||||
// newChatMessageDTOs 批量转换聊天消息,保持接口响应与数据库模型解耦。
|
||||
func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO {
|
||||
// result 是转换后的聊天消息 DTO 列表。
|
||||
@@ -738,8 +752,6 @@ type notificationChannelResponse struct {
|
||||
Name string `json:"name"`
|
||||
// Type 是通知渠道类型。
|
||||
Type string `json:"type"`
|
||||
// Config 是通知渠道配置 JSON。
|
||||
Config string `json:"config"`
|
||||
// EventTypes 是订阅事件类型 JSON 或兼容分隔文本。
|
||||
EventTypes string `json:"event_types,omitempty"`
|
||||
// Enabled 表示通知渠道是否启用。
|
||||
@@ -749,15 +761,15 @@ type notificationChannelResponse struct {
|
||||
}
|
||||
|
||||
// newNotificationChannelResponse 将数据库通知渠道转换为 HTTP DTO。
|
||||
func newNotificationChannelResponse(channel db.NotificationChannelRow) notificationChannelResponse {
|
||||
func newNotificationChannelResponse(channel notificationsapp.ChannelSummary) notificationChannelResponse {
|
||||
return notificationChannelResponse{
|
||||
ID: channel.ID, Name: channel.Name, Type: channel.Type, Config: channel.Config,
|
||||
ID: channel.ID, Name: channel.Name, Type: channel.Type,
|
||||
EventTypes: channel.EventTypes, Enabled: channel.Enabled, UserID: channel.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newNotificationChannelResponses 批量转换通知渠道,保持数据库模型不穿透 HTTP 层。
|
||||
func newNotificationChannelResponses(channels []db.NotificationChannelRow) []notificationChannelResponse {
|
||||
func newNotificationChannelResponses(channels []notificationsapp.ChannelSummary) []notificationChannelResponse {
|
||||
// result 是转换后的通知渠道 DTO 列表。
|
||||
result := make([]notificationChannelResponse, 0, len(channels))
|
||||
// channel 是当前待转换的通知渠道数据库模型。
|
||||
|
||||
Reference in new issue
Block a user