All checks were successful
CI/CD / Verify and Deploy (push) Successful in 3m23s
删除没有消费者的 SocialQueue 队列与 social.unfollow 路由键。SocialMQ 改登记 notification.social。 因此关注事件只走通知链路。social.events 不再是写库副本。 文档同步:解决方案、问题报告、写路径幂等、死信队列、项目设计。 验证:go vet ./... 通过,go test -count=1 ./... 全绿。
327 lines
17 KiB
Markdown
327 lines
17 KiB
Markdown
# P1-4 解决方案:关注只写一次库,事件只发通知
|
||
|
||
> **对应问题**:`ISSUES-REPORT.md` 的 P1-4「关注流实为 DB-first,且 worker 冗余重放写库」。
|
||
> **关联**:D-2(文档与代码不一致)、P2-13(取关的通知补偿)、P2-15(5xx 回显错误串)。
|
||
> **状态**:已实施(2026-11-11)。§3 的三项 RabbitMQ 结构改动已按批准执行。验证:`go vet ./...` 通过,`go test -count=1 ./...` 全绿;本机没有 C 编译器,`-race` 由 CI(`golang:1.24.5`)执行。
|
||
|
||
## 1. 问题
|
||
|
||
### 1.1 现象
|
||
|
||
关注和取关在“已经做过一次”时会返回 500:
|
||
|
||
| 操作 | 发生了什么 | 客户端看到的 |
|
||
|---|---|---|
|
||
| 已关注后再点关注 | `Follow` 先查 `IsFollowed`,命中后返回 `errors.New("already followed")` | 500,`{"error":"already followed"}` |
|
||
| 两个标签页同时点关注 | 两次先查都没命中,第二个 `INSERT` 撞唯一索引 | 500,`{"error":"Error 1062 (23000): Duplicate entry ..."}` |
|
||
| 已取关后再点取关 | `Unfollow` 先查 `IsFollowed`,没查到就返回 `errors.New("not followed")` | 500,`{"error":"not followed"}` |
|
||
| 每次关注成功 | `SocialWorker` 收到事件后再 `INSERT` 同一行,1062 被吞 | 无感,但多写一次库 |
|
||
| 每次取关成功 | `SocialWorker` 收到事件后再 `DELETE` 一次 | 无感,但多删一次库 |
|
||
|
||
后果:用户看到“关注失败”,但数据库里其实已经关注成功;前端可能弹错误提示或回滚按钮;MySQL 错误原文(表名、索引名)直接返回给客户端;worker 每次都在做一次无效写。
|
||
|
||
### 1.2 代码位置
|
||
|
||
`backend/internal/social/service.go` 的 `SocialService.Follow`:
|
||
|
||
```go
|
||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if isFollowed {
|
||
return errors.New("already followed")
|
||
}
|
||
|
||
// 先写 DB,确保数据持久化
|
||
if err := s.repo.Follow(ctx, social); err != nil {
|
||
return err
|
||
}
|
||
```
|
||
|
||
同一个文件的 `SocialService.Unfollow`:
|
||
|
||
```go
|
||
if !isFollowed {
|
||
return errors.New("not followed")
|
||
}
|
||
```
|
||
|
||
`backend/internal/social/repo.go` 的 `SocialRepository.Follow` 直接 `Create`,`Unfollow` 不看影响行数:
|
||
|
||
```go
|
||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) error {
|
||
return r.db.WithContext(ctx).Create(social).Error
|
||
}
|
||
|
||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error {
|
||
return r.db.WithContext(ctx).
|
||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||
Delete(&Social{}).Error
|
||
}
|
||
```
|
||
|
||
`backend/internal/worker/socialworker.go` 的 `SocialWorker.process`:
|
||
|
||
```go
|
||
case "follow":
|
||
err := w.repo.Follow(ctx, &social.Social{
|
||
FollowerID: evt.FollowerID,
|
||
VloggerID: evt.VloggerID,
|
||
})
|
||
if err == nil {
|
||
return nil
|
||
}
|
||
// 重复投递:关注关系已在,唯一索引挡下第二条。这是成功语义。
|
||
var mysqlErr *mysql.MySQLError
|
||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||
return nil
|
||
}
|
||
return err
|
||
```
|
||
|
||
### 1.3 性质
|
||
|
||
这是实现问题,不是文档问题。
|
||
|
||
- `socials` 上已经有唯一索引 `idx_social_follower_vlogger`,重复关注本来能由数据库挡下;但服务层在写之前先查了一次,把“重复”提前变成了 `error`,于是 500。
|
||
- 取关同理:“没关注过”与“关注过又删了”都返回 `not followed`,而真正该判断的是这次 `DELETE` 有没有删掉行。
|
||
- `SocialWorker` 与 API 各写一次 `socials`,两边对“重复”的处理相反:API 当错误,worker 当成功。
|
||
|
||
文档里“关注走 MQ-first、发布失败降级直写”的描述已经和代码不符(D-2),但那只是让人误判方向,不是故障根因。
|
||
|
||
## 2. 结论
|
||
|
||
1. **重复不是错误。** 关注、取关是否真的发生,交给唯一索引和影响行数回答;重复请求返回 200,响应体用 `created` / `deleted` 说明这次有没有真的改数据。
|
||
2. **`socials` 只留一个写入点。** 服务层写完库就够了,`SocialWorker` 删除。
|
||
3. **缓存失效和通知跟着“真的变了”走。** 只有这次真的插入或删除,才失效 following 缓存、才发通知。
|
||
4. **关注自己返回 400。** 它是客户端错误,不该落成 500。
|
||
5. **事件只做通知。** 只保留 `social.follow` → `notification.social`;取关不发事件。
|
||
|
||
## 3. 结构改动(已批准)
|
||
|
||
这三项会改动 RabbitMQ 拓扑,已于 2026-11-11 批准,随本次改动一起执行。
|
||
|
||
| 结构 | 是否改 | 具体改动 | 不改的后果 |
|
||
|---|---|---|---|
|
||
| MySQL 表 | 不改 | 无迁移。判重继续用现有唯一索引 `idx_social_follower_vlogger` | 只能靠预查判重,并发重复仍会 500 |
|
||
| Redis 键 | 不改 | 键名与 pattern 不动,仍是 `feed:listByFollowing:*:accountID=%d:*`。只是调用时机从“每次请求”改为“真的插入/删除” | 无 |
|
||
| 队列 `social.events` | 删 | 删除 `SocialQueue`、`SocialBindingKey` 与这条绑定 | 没有消费者,关注事件会一直留在队列里 |
|
||
| 路由键 `social.unfollow` | 删 | 删除 `SocialUnfollowRK` 与 `SocialMQ.UnFollow` | 没人订阅,发出去就丢 |
|
||
| `SocialMQ` 登记目标 | 改 | 从 `social.events` + `social.*` 改为 `notification.social` + `social.follow` | 生产者没有可登记的队列,交换机会没人声明,发布直接失败 |
|
||
|
||
为什么生产者要登记 `notification.social`:`RegisterTopology` 要求 exchange、queue、binding key 三者齐全,缺一个就跳过并打 `rabbitmq: 忽略非法拓扑`。队列和绑定必须有人先声明,消息才发得出去。API 和 worker 都会声明同一份拓扑,队列参数只由队列名推导,重复声明是幂等的。
|
||
|
||
不变的部分:交换机名 `social.events`、路由键 `social.follow`、消息体 `SocialEvent`、`notification.social` 的队列名与绑定、`NotificationWorker` 的消费与去重逻辑。
|
||
|
||
备选方案与取舍:
|
||
|
||
- **保留 worker 和队列**:现状,问题不解决。
|
||
- **只删 worker、留队列**:队列没人消费,事件无限堆积。
|
||
- **删队列,但给 `RegisterTopology` 加“只声明交换机”的能力**:改的是共享拓扑工具,影响所有业务方,收益只是省一个队列登记。
|
||
- **推荐**:按上表删除队列与取关路由键,生产者改登记 `notification.social`。
|
||
|
||
已确认:
|
||
|
||
1. 删除 `social.events` 队列与 `social.unfollow` 路由键,生产者改登记 `notification.social`。
|
||
2. 仓库内只有 `SocialWorker` 一个消费者;若仓库外另有订阅 `social.events` 的消费者,发布前需要通知对方(部署侧确认)。
|
||
3. 发布后手工删除线上残留的 `social.events`、`social.events.retry`、`retry.events.social.events`。
|
||
|
||
## 4. 需求与边界
|
||
|
||
| # | 需求 |
|
||
|---|---|
|
||
| R1 | 重复关注返回 200,`created` 为 `false`;响应体不再出现 `Duplicate entry` 或 `already followed` |
|
||
| R2 | 重复取关返回 200,`deleted` 为 `false`,不再出现 `not followed` |
|
||
| R3 | 关注自己返回 400,且不写库、不发消息 |
|
||
| R4 | 只有这次真的插入或删除,才失效 following 缓存、才发通知 |
|
||
| R5 | 首次关注仍给被关注者生成一条通知;发通知失败不影响已成功的关注 |
|
||
| R6 | 唯一索引之外的数据库错误仍向上返回,不被当成“重复”吞掉 |
|
||
| R7 | `socials` 只有服务层一个写入点,worker 不再写库 |
|
||
|
||
本次不做:
|
||
|
||
- 取关、删评论的通知补偿(P2-13)。
|
||
- 5xx 响应去掉错误原文(P2-15)。
|
||
- 删除 `IsFollowed` 死代码(报告第八节,第四阶段统一清)。
|
||
- 去掉两次 `FindByID`。`VloggerID` 不存在必须仍是 404。
|
||
- 加事务。单条 `INSERT` / `DELETE` 本身原子,加事务只会把两段拆开的操作重新绑在一起。
|
||
|
||
## 5. 方案
|
||
|
||
### 5.1 仓储层:让数据库回答“有没有变”
|
||
|
||
```go
|
||
// Follow 返回本次是否真的插入:重复关注是幂等成功,不是错误。
|
||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) {
|
||
res := r.db.WithContext(ctx).
|
||
Clauses(clause.OnConflict{DoNothing: true}).
|
||
Create(social)
|
||
if res.Error != nil {
|
||
return false, res.Error
|
||
}
|
||
return res.RowsAffected > 0, nil
|
||
}
|
||
|
||
// Unfollow 用影响行数回答“这次是否真的删掉”:第二次取关是空操作。
|
||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||
res := r.db.WithContext(ctx).
|
||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||
Delete(&Social{})
|
||
if res.Error != nil {
|
||
return false, res.Error
|
||
}
|
||
return res.RowsAffected > 0, nil
|
||
}
|
||
```
|
||
|
||
GORM 的 MySQL 方言把 `OnConflict{DoNothing}` 编译成 `ON DUPLICATE KEY UPDATE id=id`,不是 `INSERT IGNORE`:唯一键冲突时影响行数为 0,其他错误照常返回。前提是 DSN 不开 `clientFoundRows`,`internal/db/db.go` 的注释和单测已经钉住这一点。
|
||
|
||
### 5.2 服务层:唯一写入点,按结果决定副作用
|
||
|
||
```go
|
||
func (s *SocialService) Follow(ctx context.Context, social *Social) (bool, error) {
|
||
if social.FollowerID == social.VloggerID {
|
||
return false, ErrCannotFollowSelf
|
||
}
|
||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||
return false, err
|
||
}
|
||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||
return false, err
|
||
}
|
||
|
||
created, err := s.repo.Follow(ctx, social)
|
||
if err != nil {
|
||
return false, err
|
||
}
|
||
if !created {
|
||
// 关系已在,缓存和通知都已经是“已关注”状态。
|
||
return false, nil
|
||
}
|
||
|
||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||
}
|
||
return true, nil
|
||
}
|
||
```
|
||
|
||
`Unfollow` 结构相同,返回 `(deleted bool, err error)`,去掉发通知那一段。两点说明:
|
||
|
||
- 自关注检查放到最前,不依赖数据库。
|
||
- 缓存失效仍用 `context.Background()`:请求可能已被客户端取消,但行已经写进去了。
|
||
|
||
为了能写单测,`SocialService` 的依赖收窄成三个接口(`socialStore`、`accountFinder`、`followNotifier`),`router.go` 的调用点不用改。`*rabbitmq.SocialMQ` 在 nil 接收者上返回 error,所以 MQ 没启用时只会多一条日志,不会把已经写成功的关注变成失败。
|
||
|
||
### 5.3 handler:自关注映射成 400
|
||
|
||
```go
|
||
func classifySocialError(err error) int {
|
||
if errors.Is(err, ErrCannotFollowSelf) {
|
||
return http.StatusBadRequest
|
||
}
|
||
return apierror.ClassifyHTTPStatus(err)
|
||
}
|
||
```
|
||
|
||
其余错误仍走 `ClassifyHTTPStatus`。`SocialHandler.Follow` 与 `Unfollow` 把布尔值写进响应:
|
||
|
||
```go
|
||
created, err := h.service.Follow(c.Request.Context(), social)
|
||
if err != nil {
|
||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"message": "followed", "created": created})
|
||
```
|
||
|
||
`Unfollow` 对应 `deleted` 与 `"unfollowed"`。
|
||
|
||
### 5.4 事件:只发关注通知
|
||
|
||
```go
|
||
const (
|
||
SocialExchange = "social.events"
|
||
SocialFollowRK = "social.follow"
|
||
)
|
||
|
||
func NewSocialMQ(base *RabbitMQ) (*SocialMQ, error) {
|
||
if base == nil {
|
||
return nil, errors.New("rabbitmq base is nil")
|
||
}
|
||
base.RegisterTopology(Topology{
|
||
Exchange: SocialExchange,
|
||
Queue: NotificationSocialQueue,
|
||
BindingKey: SocialFollowRK,
|
||
})
|
||
return &SocialMQ{mgr: base}, nil
|
||
}
|
||
```
|
||
|
||
### 5.5 删除 `SocialWorker`
|
||
|
||
删 `backend/internal/worker/socialworker.go`,同时去掉 `cmd/worker` 里的三处:第一批 `RegisterTopology` 中的 social 拓扑、`socialRepo` 与 `internal/social` import、`RunConsumer(..., "SocialWorker", 50, ...)`。
|
||
|
||
## 6. 副作用与取舍
|
||
|
||
- **重复点击不再刷新缓存。** 行没变,列表就没变;但如果上一次失效本身失败了,要等下一次真实变更或缓存过期才恢复。
|
||
- **取关后旧通知仍在。** 关注通知不会撤回,这是 P2-13 的缺口。
|
||
- **通知可能丢。** 关注已经落库但发布失败时只记日志,没有 outbox 和重试。
|
||
- **其他数据库错误仍是 500 且带原文。** 例如连接中断、字段超长,脱敏属于 P2-15。
|
||
- **`ON DUPLICATE KEY UPDATE` 对任何唯一键冲突都不报错。** `socials` 目前只有 `idx_social_follower_vlogger` 一个唯一索引,成立;以后加第二个唯一索引要重新评估。
|
||
- **自增 ID 会有空洞。** 冲突的 `INSERT` 仍会推进 `AUTO_INCREMENT`,与评论路径一致。
|
||
- **为什么不返回 409。** 重复是正常语义,不是冲突;前端会把 409 当失败弹提示。
|
||
- **为什么不用 1062 判重。** 项目已有更直接的写法(`OnConflict` + 影响行数),`docs/design/写路径幂等.md` 也写明不用 1062。两种写法并存会让两条写路径风格分裂。
|
||
- **响应体只新增字段。** `message` 保留,`created` / `deleted` 是增量,前端不解析也不受影响。
|
||
|
||
## 7. 测试
|
||
|
||
单测用 fake 驱动,不需要 MySQL 和 broker:
|
||
|
||
| 测试 | 断言 |
|
||
|---|---|
|
||
| `TestSocialService_Follow_SecondCallIsNoop` | 首次 `(true, nil)`、通知 1 条;重复 `(false, nil)`、通知仍是 1 条 |
|
||
| `TestSocialService_Follow_SelfIsRejected` | `(false, ErrCannotFollowSelf)`,写库 0 次 |
|
||
| `TestSocialService_Follow_RepoErrorPropagates` | 仓储报错 → 原样返回,通知 0 次 |
|
||
| `TestSocialService_Follow_NotifyFailureKeepsSuccess` | 发通知失败 → `(true, nil)` |
|
||
| `TestSocialService_Follow_AccountLookupErrorPropagates` | 账号查询失败 → 原样返回,写库 0 次 |
|
||
| `TestSocialService_Unfollow_SecondCallIsNoop` | `(false, nil)` |
|
||
| `TestSocialHandler_Follow_SelfReturnsBadRequest` | 状态码 400,响应体含 `can not follow self` |
|
||
| `TestSocialHandler_Follow_DuplicateReturnsOK` | 状态码 200,响应体 `created` 为 `false` |
|
||
| `TestSocialHandler_Unfollow_DuplicateReturnsOK` | 状态码 200,响应体 `deleted` 为 `false` |
|
||
|
||
`TestSocialService_*` 用 fake 的 `socialStore`、`accountFinder`、`followNotifier`;handler 测试用 `gin.CreateTestContext` 加 `c.Set("accountID", uint(1))`。
|
||
|
||
仓储的判重行为对着真 MySQL 验证,放 `//go:build integration`,沿用 `commentworker_integration_test.go` 的做法(`MYSQL_TEST_DSN` 缺失就 `t.Skip`,DSN 带 `clientFoundRows` 直接失败):
|
||
|
||
| 测试 | 断言 |
|
||
|---|---|
|
||
| `TestSocialRepository_Follow_DuplicateReportsNotCreated` | 插两次:`true` → `false`,都无 error,表里 1 行 |
|
||
| `TestSocialRepository_Unfollow_SecondCallReportsNotDeleted` | 删两次:`true` → `false`,都无 error |
|
||
|
||
手工验收:连点两次关注、两次取关各返回两个 200;关注自己返回 400;被关注者只有一条通知;`rabbitmqctl list_queues` 里没有 `social.events`。
|
||
|
||
**验证记录(2026-11-11)**:`go vet ./...` 通过;`go test -count=1 ./...` 全绿,`internal/social` 与 `internal/middleware/rabbitmq` 均 ok。集成测试对 MySQL 8.0 通过(`MYSQL_TEST_DSN` 指向 `feedsystem_test`),确认重复插入返回 `created=false`、第二次删除返回 `deleted=false`。本机 `CGO_ENABLED=0` 且没有 C 编译器,未跑 `-race`,由 CI(`golang:1.24.5`)执行 `go test -race -count=1 ./...`。
|
||
|
||
## 8. 改动清单
|
||
|
||
| 文件 | 改动 |
|
||
|---|---|
|
||
| `backend/internal/social/repo.go` | `Follow`、`Unfollow` 返回 `(bool, error)` |
|
||
| `backend/internal/social/service.go` | 删掉两处先查;新增 `ErrCannotFollowSelf` 与三个窄接口;`Follow` / `Unfollow` 返回 `(bool, error)`,按结果决定失效缓存和发通知;`Unfollow` 不再发事件 |
|
||
| `backend/internal/social/handler.go` | 新增 `classifySocialError`;响应体加 `created` / `deleted` |
|
||
| `backend/internal/social/service_test.go` | 新增 §7 的单测 |
|
||
| `backend/internal/social/handler_test.go` | 新增自关注 400、重复关注 200 |
|
||
| `backend/internal/social/repo_integration_test.go` | 新增集成测试 |
|
||
| `backend/internal/worker/socialworker.go` | 删除 |
|
||
| `backend/cmd/worker/main.go` | 删 SocialWorker 启动、`socialRepo`、social 拓扑与 import |
|
||
| `backend/internal/middleware/rabbitmq/socialMQ.go` | 删 `SocialQueue`、`SocialBindingKey`、`SocialUnfollowRK`、`UnFollow`;登记改 `notification.social` |
|
||
| `backend/internal/middleware/rabbitmq/constants_test.go` | 删三个常量的断言 |
|
||
| `backend/internal/middleware/rabbitmq/notification.go` | 注释补一句“关注没有 DB 同步队列” |
|
||
| `docs/design/写路径幂等.md` | §1 把关注从 MQ-first 里拆出来,写明判重键与 `created` / `deleted` |
|
||
| `docs/design/消息处理失败与死信队列.md` | 业务队列 8 个改 7 个 |
|
||
| `docs/feedsystem_video_go项目设计.md` | 事件表、接口表、消费者表、`mq_topology` 期望值(Worker 7 → 6) |
|
||
| `docs/ISSUES-REPORT.md` | P1-4 标 ✅ 并补“解决”段与索引;D-2 更新 |
|