2026-10-31 00:03:52 +08:00
|
|
|
|
# 项目保证写路径幂等:全链路实现
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
本文只讲"当前代码如何做到只生效一次",按一次真实请求的顺序展开,逐层给出关键源码与取舍理由。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
## 1. 写路径的重复是结构性的
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
点赞、评论、关注都走"先发消息,失败再直写数据库"。这条路径上,重复不是异常,而是常态:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
| 重复来源 | 触发条件 | 是否可避免 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| 发布返回错误但 broker 已收下 | 网络超时、channel 抖动、发布后进程崩溃 | 不可完全避免 |
|
|
|
|
|
|
| 队列重复投递 | 消费端处理完但 Ack 丢失、重试队列回源 | 不可完全避免 |
|
|
|
|
|
|
| 客户端重试 | 用户连点、请求超时后重发 | 不可完全避免 |
|
|
|
|
|
|
| 直写与消费双写 | 发布失败 → 直写;消息其实也到了 | 由设计决定 |
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
前三种是分布式系统固有属性,第四种是"降级路径"的必然代价。因此幂等不能寄希望于"只写一次",只能定义成:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
> 同一次用户意图被执行任意多次,每个副作用的结果与执行一次相同。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
副作用有三个,必须分别守住:评论行、视频热度、通知。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
## 2. 核心概念:意图键
|
|
|
|
|
|
|
|
|
|
|
|
**一次用户动作 = 一个键。** 这个键要在四个地方存活:HTTP 请求、消息体、数据库行、通知去重键。任何一处丢失,对应的那层判重就失效。
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
### 2.1 生成:`NewIntentKey`
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/video/idempotency.go
|
|
|
|
|
|
func NewIntentKey() (string, error) {
|
|
|
|
|
|
b := make([]byte, 16)
|
|
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
|
|
return "", fmt.Errorf("generate intent key: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
return hex.EncodeToString(b), nil
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
16 字节随机数编码成 32 个十六进制字符。三点说明:
|
|
|
|
|
|
|
|
|
|
|
|
- **不引 uuid 依赖。** 项目当前没有该依赖,`crypto/rand` + `hex` 已满足"不可预测且不碰撞"。
|
|
|
|
|
|
- **不复用 `rabbitmq.newEventID`。** 它逻辑相同,但在包内私有;跨包导出会把 `video` 拖进 `rabbitmq → config` 的依赖链,为一个 8 行函数不值。
|
|
|
|
|
|
- **长度上限钉在 64。** 与 `comments.idempotency_key VARCHAR(64)` 一致,避免"键能生成但列存不下"。
|
|
|
|
|
|
|
|
|
|
|
|
### 2.2 校验:`validateIntentKey`
|
|
|
|
|
|
|
|
|
|
|
|
规则:长度 8–64,字符集 `[0-9a-zA-Z_-]`。
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
const (
|
|
|
|
|
|
MaxIntentKeyLen = 64
|
|
|
|
|
|
minIntentKeyLen = 8
|
|
|
|
|
|
intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
|
|
|
|
|
|
)
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
四条约束各有原因:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
| 约束 | 原因 |
|
|
|
|
|
|
|---|---|
|
|
|
|
|
|
| 最小 8 字符 | 挡住 `"1"`、`"a"` 这类极易碰撞的键;短键会让两个用户的提交意外合并 |
|
|
|
|
|
|
| 排除 `:` | 通知去重键用 `:` 分段(`mention:<键>:<收件人>`),键里带 `:` 会让边界不可解析 |
|
|
|
|
|
|
| 非法直接报错,不截断不替换 | 静默修正会造出"客户端以为去重了、服务端其实没有",比重复更难排查 |
|
|
|
|
|
|
| 错误必须包 `apierror.ErrValidation` | `ClassifyHTTPStatus` 只对 `ErrValidation` 返回 400,裸 error 会落 500,把参数错误显示成服务端故障 |
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
最后一条容易写漏,写漏的表现是"用户传错 `request_id` 却收到 500",看起来像后端崩溃:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
return fmt.Errorf("%w: request_id must be %d-%d characters",
|
|
|
|
|
|
apierror.ErrValidation, minIntentKeyLen, MaxIntentKeyLen)
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
### 2.3 解析:`ResolveIntentKey`
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func ResolveIntentKey(raw *string) (string, error) {
|
|
|
|
|
|
if raw == nil || strings.TrimSpace(*raw) == "" {
|
|
|
|
|
|
return NewIntentKey()
|
|
|
|
|
|
}
|
|
|
|
|
|
key := strings.TrimSpace(*raw)
|
|
|
|
|
|
if err := validateIntentKey(key); err != nil {
|
|
|
|
|
|
return "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
return key, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
三条分支对应三种客户端:
|
|
|
|
|
|
|
|
|
|
|
|
| 输入 | 结果 | 语义 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| `nil` / 空白 | 生成新键 | 旧客户端;单次请求内仍然一致,但客户端侧的重试无法被识别 |
|
|
|
|
|
|
| 合法值 | 原样返回 | 客户端重试携带同一个值 → 命中同一次意图 |
|
|
|
|
|
|
| 非法值 | 返回 400 | 不猜测用户意图 |
|
|
|
|
|
|
|
|
|
|
|
|
### 2.4 一次评论请求里,键是怎么流转的
|
|
|
|
|
|
|
|
|
|
|
|
键不是"传到某一层就算完",它要横穿整条请求。下面按实际调用顺序展开。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
**第 1 跳:HTTP 层把客户端的值放进实体。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/video/comment_handler.go
|
|
|
|
|
|
comment := &Comment{Username: user.Username, VideoID: req.VideoID, AuthorID: authorId, Content: req.Content}
|
|
|
|
|
|
if req.RequestID != "" {
|
|
|
|
|
|
requestID := req.RequestID
|
|
|
|
|
|
comment.IdempotencyKey = &requestID
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
这一跳只做搬运,不校验、不生成:判断与生成统一放在服务层,避免两处规则漂移。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
**第 2 跳:服务层解析,并把它写回实体。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/video/comment_service.go — Publish
|
|
|
|
|
|
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err // 非法 request_id 已包 apierror.ErrValidation,落 400
|
|
|
|
|
|
}
|
2026-10-31 00:03:52 +08:00
|
|
|
|
comment.IdempotencyKey = &key
|
2026-10-30 23:48:47 +08:00
|
|
|
|
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
回写是这条链路的关键动作。`comment` 这个指针之后会被兜底写入直接使用;如果键只存在局部变量里,兜底路径拿到的就是 `nil`,它会退化成"每次都是新意图",唯一的幂等保护当场消失。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
`span` 是同一意图的日志前缀,API 与 Worker 两侧都打印它:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func logIntent(stage, key string, authorID, videoID uint) string {
|
|
|
|
|
|
return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID)
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
线上排查时用 `grep intent_key=<K>` 可以把一次提交在 API 与 Worker 两侧的日志串起来。
|
|
|
|
|
|
|
2026-10-30 23:48:47 +08:00
|
|
|
|
**第 3 跳:事件携带同一个键。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
|
2026-10-31 00:03:52 +08:00
|
|
|
|
EventID: key,
|
|
|
|
|
|
Action: "publish",
|
|
|
|
|
|
Username: comment.Username,
|
|
|
|
|
|
VideoID: comment.VideoID,
|
|
|
|
|
|
AuthorID: comment.AuthorID,
|
|
|
|
|
|
Content: comment.Content,
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}); err == nil {
|
|
|
|
|
|
commentEnqueued = true
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
发布函数本身不生成键,只在键为空时补一个随机值兜底:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/middleware/rabbitmq/commentMQ.go
|
|
|
|
|
|
func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt CommentEvent) error {
|
|
|
|
|
|
...
|
2026-10-31 00:03:52 +08:00
|
|
|
|
if evt.EventID == "" {
|
2026-10-30 23:48:47 +08:00
|
|
|
|
id, err := newEventID(16)
|
|
|
|
|
|
...
|
|
|
|
|
|
evt.EventID = id
|
|
|
|
|
|
}
|
2026-10-31 00:03:52 +08:00
|
|
|
|
evt.Action = action
|
|
|
|
|
|
evt.OccurredAt = time.Now().UTC()
|
|
|
|
|
|
return c.mgr.PublishJSON(ctx, CommentExchange, routingKey, evt)
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
如果发布函数"总是自己生成",事件里的键与兜底写入的键必然不同,消费端再判重也无从命中。这个错误在没有业务测试覆盖时完全看不出来。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**第 4 跳:兜底写入用的是同一个实体、同一个键。**
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
2026-10-31 00:03:52 +08:00
|
|
|
|
if !commentEnqueued {
|
2026-10-30 23:48:47 +08:00
|
|
|
|
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
|
|
|
|
|
...
|
2026-10-31 00:03:52 +08:00
|
|
|
|
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
传的是 `comment` 本身,不是重新组装的结构体——键在第 2 跳已经写进它了。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**第 5 跳:数据库用唯一索引裁决,用"是否真的插入"门控副作用。**
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/video/comment_repo.go
|
|
|
|
|
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
|
|
|
|
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
|
|
|
|
|
|
if res.Error != nil {
|
|
|
|
|
|
return res.Error
|
|
|
|
|
|
}
|
|
|
|
|
|
if res.RowsAffected == 0 {
|
2026-10-31 00:03:52 +08:00
|
|
|
|
return nil
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
created = true
|
2026-10-31 00:03:52 +08:00
|
|
|
|
if delta == 0 {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
2026-10-30 23:48:47 +08:00
|
|
|
|
return tx.Model(&Video{}).Where("id = ?", c.VideoID).
|
|
|
|
|
|
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
|
|
|
|
|
|
})
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
`created` 是可观测的结果,不是假设。消费端拿到的是同一件事:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// backend/internal/worker/commentworker.go
|
|
|
|
|
|
c := &video.Comment{Username: ..., VideoID: evt.VideoID, AuthorID: evt.AuthorID, Content: ...}
|
|
|
|
|
|
if evt.EventID != "" {
|
|
|
|
|
|
key := evt.EventID
|
2026-10-31 00:03:52 +08:00
|
|
|
|
c.IdempotencyKey = &key
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1)
|
|
|
|
|
|
if !created {
|
2026-10-31 00:03:52 +08:00
|
|
|
|
log.Printf("comment worker: dedupe=hit event_id=%s video_id=%d author_id=%d",
|
|
|
|
|
|
evt.EventID, evt.VideoID, evt.AuthorID)
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
API 直写过 → Worker 的插入返回 `created=false`,热度不重复;反过来也一样。谁先到都成立。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
**第 6 跳:由同一个键派生出通知去重键。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
mentions = append(mentions, Mention{
|
|
|
|
|
|
RecipientID: id,
|
|
|
|
|
|
SenderID: comment.AuthorID,
|
|
|
|
|
|
TargetID: comment.VideoID,
|
|
|
|
|
|
Content: comment.Username + " 在评论中提到了你",
|
2026-10-31 00:03:52 +08:00
|
|
|
|
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
2026-10-30 23:48:47 +08:00
|
|
|
|
})
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
派生函数只做拼接,但有一条硬约束:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
|
|
|
|
|
|
if intentKey == "" {
|
2026-10-31 00:03:52 +08:00
|
|
|
|
return ""
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
空键返回空串,最终通过 `nilIfEmpty` 写成 `NULL`,不参与唯一索引——退化为"不去重",而不是让所有无键通知撞在同一个键上。
|
|
|
|
|
|
|
2026-10-30 23:48:47 +08:00
|
|
|
|
**最后一跳:把键回显给客户端。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
resp := gin.H{"message": "comment published successfully"}
|
|
|
|
|
|
if comment.IdempotencyKey != nil {
|
2026-10-31 00:03:52 +08:00
|
|
|
|
resp["request_id"] = *comment.IdempotencyKey
|
2026-10-30 23:48:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
客户端不传 `request_id` 时,服务端在第 2 跳生成了一个并在这里回显。客户端只有拿到它,下一次重试才能声明"这还是同一次意图"。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
载体对照:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
| 跳 | 载体 | 字段 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| HTTP 入参 | 请求体 | `request_id` |
|
|
|
|
|
|
| 服务层实体 | `*Comment` | `IdempotencyKey` |
|
|
|
|
|
|
| 评论事件 | 消息体 | `event_id` |
|
|
|
|
|
|
| 兜底写入 | SQL 参数 | `comments.idempotency_key` |
|
|
|
|
|
|
| 消费端 | 消息体 → 实体 | `event_id` → `IdempotencyKey` |
|
|
|
|
|
|
| 通知 | 派生字符串 | `notifications.dedupe_key` |
|
|
|
|
|
|
|
|
|
|
|
|
中间任何一跳丢了这个值,后面的判重就全部失效——而失效的表现是"偶尔重复一条",不会报错。
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
## 3. 数据库层:唯一索引 + 单事务
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
### 3.1 字段与索引形状
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
type Comment struct {
|
|
|
|
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
|
|
|
|
Username string `gorm:"index" json:"username"`
|
|
|
|
|
|
VideoID uint `gorm:"index" json:"video_id"`
|
|
|
|
|
|
AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"`
|
|
|
|
|
|
Content string `gorm:"type:text" json:"content"`
|
|
|
|
|
|
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
|
|
|
|
|
|
|
|
|
|
|
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
四个细节:
|
|
|
|
|
|
|
|
|
|
|
|
**① 唯一键是 `(author_id, idempotency_key)`,不是只有键。** 只按键唯一会让两个用户偶然拿到同一个 `request_id` 时互相顶掉;带上作者维度,判重范围恰好是"同一个人的同一次意图"。
|
|
|
|
|
|
|
|
|
|
|
|
**② 必须是 `*string`,不能是 `string`。** MySQL 唯一索引不约束 `NULL`,多个 `NULL` 可以共存;空串则会互相冲突。若用 `string` + `''`,所有"没带 `request_id`"的评论会撞在同一个键上,第二条正常评论就被判成重复。转空串为 `NULL` 的动作由 `nilIfEmpty` 统一负责。
|
|
|
|
|
|
|
|
|
|
|
|
**③ `json:"-"`。** 它是去重机制的内部标识,不属于用户可见数据;出现在 API 响应里只会诱使客户端把它当业务字段使用。
|
|
|
|
|
|
|
|
|
|
|
|
**④ `AuthorID` 上同时保留 `index` 与 `uniqueIndex`。** 复合索引 `(author_id, idempotency_key)` 的**最左前缀**能以 `author_id` 为条件服务查询,但方向只有一个:单列索引不能顶替复合索引。`index` 标签因此是冗余索引,暂时保留以免混入无收益的 schema 抖动。
|
|
|
|
|
|
|
|
|
|
|
|
### 3.2 写入:一条 SQL 决出胜负
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
|
|
|
|
|
|
var created bool
|
|
|
|
|
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
|
|
|
|
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
|
|
|
|
|
|
...
|
|
|
|
|
|
})
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
为什么不"先 SELECT 再 INSERT":
|
|
|
|
|
|
|
|
|
|
|
|
- 两个 goroutine 之间永远有窗口,而这个窗口正好就是本设计要覆盖的场景(MQ 假失败后兜底直写 + worker 稍后消费)。
|
|
|
|
|
|
- 唯一索引把"查"和"写"合并成一个原子动作,窗口不存在。
|
|
|
|
|
|
|
|
|
|
|
|
为什么不用 1062 判重:
|
|
|
|
|
|
|
|
|
|
|
|
- 报错与去重是两种语义。用报错表达去重会让每条正常路径都经过一次 error 分支。
|
|
|
|
|
|
- 1062 也可能来自别的唯一键,需要再解析错误内容才能区分。
|
|
|
|
|
|
- `OnConflict{DoNothing}` 直接给出 `RowsAffected`,它就是"我是否真的插入了"的答案。
|
|
|
|
|
|
|
|
|
|
|
|
### 3.3 为什么两个写必须同事务
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if res.RowsAffected == 0 {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
created = true
|
|
|
|
|
|
if delta == 0 {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
return tx.Model(&Video{}).Where("id = ?", c.VideoID).
|
|
|
|
|
|
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
如果拆成两条独立语句,它们之间崩溃就会留下"评论在、热度不在"的半成品:重投时评论命中唯一索引(`created=false`),热度永远不会补上。放进同一个事务后,两种结果只有"都在"或"都不在"。
|
|
|
|
|
|
|
|
|
|
|
|
`GREATEST(...,0)` 防止热度被减到负数——删除路径复用同一个函数时,负值会让排行榜出现异常条目。
|
|
|
|
|
|
|
|
|
|
|
|
### 3.4 三个容易踩的坑
|
|
|
|
|
|
|
|
|
|
|
|
**① `clientFoundRows` 会让判重静默失效。** 该选项让 MySQL 在"行未变化"时也报告影响 1 行,于是 `RowsAffected == 0` 这个判断永远不成立,重复写入被当成首次写入,热度变成 +2。项目 DSN(`internal/db/db.go`)刻意不开启它,`BuildDSN` 有一条单测钉住这一条:
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func TestBuildDSN_DoesNotEnableClientFoundRows(t *testing.T)
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
**② 冲突会消耗自增 ID。** `OnConflict DoNothing` 的插入在冲突时仍会推进 `AUTO_INCREMENT`,`comments.id` 因此出现空洞。这是可接受的代价:ID 只用于标识,不承诺连续。
|
|
|
|
|
|
|
|
|
|
|
|
**③ `RowsAffected` 是"这次调用插入了"的唯一可信来源。** 不要用"插入后再查一次是否存在"来判断,那会重新引入窗口,也让日志无法区分 `dedupe=hit` 与 `dedupe=miss`。
|
|
|
|
|
|
|
|
|
|
|
|
### 3.5 删除路径
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
|
|
|
|
|
|
if id == 0 {
|
|
|
|
|
|
return false, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
res := r.db.WithContext(ctx).Delete(&Comment{}, id)
|
|
|
|
|
|
if res.Error != nil {
|
|
|
|
|
|
return false, res.Error
|
|
|
|
|
|
}
|
|
|
|
|
|
return res.RowsAffected > 0, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
返回 `deleted bool` 的理由与新增对称:把热度回退当成无条件动作,同一条删除事件投递两次就会把热度减两次。`deleted` 是该回退的门控点。
|
|
|
|
|
|
|
|
|
|
|
|
## 4. 服务层:两条路径的编排
|
|
|
|
|
|
|
|
|
|
|
|
### 4.1 三个最小接口
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
type CommentPublisher interface {
|
|
|
|
|
|
Publish(ctx context.Context, evt rabbitmq.CommentEvent) error
|
|
|
|
|
|
Delete(ctx context.Context, commentID uint, intentKey string) error
|
|
|
|
|
|
}
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
type PopularityPublisher interface {
|
|
|
|
|
|
Update(ctx context.Context, videoID uint, change int64, intentKey string) error
|
|
|
|
|
|
}
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
type videoExister interface {
|
|
|
|
|
|
IsExist(ctx context.Context, id uint) (bool, error)
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
它们不是为了"面向接口编程",各有具体理由:
|
|
|
|
|
|
|
|
|
|
|
|
| 接口 | 存在理由 |
|
|
|
|
|
|
|---|---|
|
|
|
|
|
|
| `CommentPublisher` / `PopularityPublisher` | P0-4 的全部分支都取决于"这条消息到底发出去了没有",而这恰恰是真实 broker 最难稳定复现的状态。只有替身才能确定性触发"发布失败"分支 |
|
|
|
|
|
|
| `videoExister` | 4 行代码,但 `Publish` 第一句就是 `IsExist`。删掉它,服务层所有用例都会退化成集成测试 |
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
`*VideoRepository` 天然满足 `videoExister`,因此 `router.go` 的构造代码不需要改。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**nil 接收者陷阱:** nil 指针装进接口后 `iface != nil` 依然为 true。所以真实实现必须在 nil 接收者上返回 error,否则"MQ 未初始化"会被当成"发布成功",直接跳过兜底。
|
|
|
|
|
|
|
|
|
|
|
|
### 4.2 `Publish` 的完整分支
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
|
|
|
|
|
if comment == nil {
|
|
|
|
|
|
return errors.New("comment is nil")
|
|
|
|
|
|
}
|
|
|
|
|
|
comment.Content = strings.TrimSpace(comment.Content)
|
|
|
|
|
|
comment.Username = strings.TrimSpace(comment.Username)
|
|
|
|
|
|
if comment.Content == "" || comment.VideoID == 0 || comment.AuthorID == 0 {
|
|
|
|
|
|
return fmt.Errorf("%w: video_id, author_id and content are required", apierror.ErrValidation)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
|
|
|
|
|
...
|
2026-10-30 23:48:47 +08:00
|
|
|
|
```
|
2026-10-31 00:03:52 +08:00
|
|
|
|
|
|
|
|
|
|
**校验顺序:** 先 TrimSpace 再判空。让 `" "` 落进"内容为空"分支,而不是变成一条空白评论。
|
|
|
|
|
|
|
|
|
|
|
|
**闸 1:只有评论事件没入队时才直写。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if !commentEnqueued {
|
|
|
|
|
|
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("fallback create comment: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
|
|
|
|
|
}
|
2026-10-30 23:48:47 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
入队成功时 API 不写库。这条规则是"避免稳定双写"的关键:如果入队成功也写,正常路径上每条评论都会写两次,幂等索引只能保证行不重复,却让热度与通知的判重长期处于"永远命中"的状态,反而掩盖真实问题。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**闸 2:热度兜底与评论事件彼此独立。**
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
if !popularityEnqueued {
|
|
|
|
|
|
if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil {
|
|
|
|
|
|
log.Printf("%s hot cache update failed (degraded): %v", span, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
两条事件是两次独立发布,`commentEnqueued` 与 `popularityEnqueued` 必须分开判断。热度是"近似正确"的派生数据:更新失败只降级、不回滚评论,也不把一次成功发布变成 500。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**发布失败不等于没送达。** 短超时、channel 抖动都可能发生在 broker 已收下之后。因此不能根据 error 决定"要不要写",只能让两条路径共用同一个键,由唯一索引吸收重复。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**日志三元组。** 一次请求最多留下三条与判重有关的日志:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
| 日志 | 含义 |
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|---|---|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
| `enqueue comment failed, fallback to direct write` | 走了兜底路径 |
|
|
|
|
|
|
| `fallback write dedupe=miss` / `dedupe=hit` | 兜底时是否真的插入 |
|
|
|
|
|
|
| `hot cache update failed (degraded)` | 热度未写,但请求成功 |
|
|
|
|
|
|
|
|
|
|
|
|
`dedupeLabel` 把 `created bool` 翻成 `miss`/`hit`:
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
func dedupeLabel(created bool) string {
|
|
|
|
|
|
if created {
|
|
|
|
|
|
return "miss"
|
|
|
|
|
|
}
|
|
|
|
|
|
return "hit"
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
### 4.3 `Delete`
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
key, keyErr := NewIntentKey()
|
|
|
|
|
|
if keyErr != nil {
|
|
|
|
|
|
key = ""
|
|
|
|
|
|
}
|
|
|
|
|
|
if err := s.commentMQ.Delete(ctx, commentID, key); err == nil {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
return s.store.DeleteComment(ctx, comment)
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
- 删除事件的 `event_id` 也用意图键。删除的幂等不靠这个键,而是靠消费端的 `DeleteByID` 返回的 `deleted bool`——同一条删除事件投递两次,第二次是空操作。
|
|
|
|
|
|
- 键生成失败时用空串:删除路径不依赖该键,不能因为随机数失败让用户删不掉评论。
|
|
|
|
|
|
- 权限检查在删除之前:`comment.AuthorID != accountID` 返回 `apierror.ErrUnauthorized`。这个检查对两类重复都成立——重复投递的删除在消费端是空操作,重复点击删除在 API 侧是先查后删。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
### 4.4 `GetAll`
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
先 `IsExist` 再查列表:视频不存在时返回 400,而不是返回空列表。空列表会让前端把"视频没了"显示成"还没有评论"。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
## 5. 通知层
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
### 5.1 `notifyMentions` 的三段式
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
|
|
|
|
|
|
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
|
|
|
|
|
|
...
|
|
|
|
|
|
ids, err := s.store.FindAccountIDs(ctx, names)
|
|
|
|
|
|
...
|
|
|
|
|
|
if err := s.store.CreateMentions(ctx, mentions); err != nil {
|
|
|
|
|
|
log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**第一段:解析并去重用户名。**
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
for _, m := range matches {
|
|
|
|
|
|
name := m[1]
|
|
|
|
|
|
if name == comment.Username {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
if _, dup := seen[name]; dup {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
seen[name] = struct{}{}
|
|
|
|
|
|
names = append(names, name)
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
跳过自己是必须的:`@自己` 不该产生通知。注意这里按 **username** 跳过,因为此刻还没有 ID;后面查回 ID 后还要再按 ID 跳过一次(见下)。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**第二段:一次批量查询。**
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
```go
|
|
|
|
|
|
ids, err := s.store.FindAccountIDs(ctx, names)
|
|
|
|
|
|
```
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
逐个 `SELECT` 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在用户请求路径上。不存在的用户名不出现在结果里,调用方按 map 的不存在分支跳过。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
**第三段:批量写入,每条带去重键。**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
for _, name := range names {
|
|
|
|
|
|
id, ok := ids[name]
|
|
|
|
|
|
if !ok || id == 0 {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
if id == comment.AuthorID {
|
|
|
|
|
|
continue
|
|
|
|
|
|
}
|
|
|
|
|
|
mentions = append(mentions, Mention{
|
|
|
|
|
|
RecipientID: id,
|
|
|
|
|
|
SenderID: comment.AuthorID,
|
|
|
|
|
|
TargetID: comment.VideoID,
|
|
|
|
|
|
Content: comment.Username + " 在评论中提到了你",
|
|
|
|
|
|
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
去重键必须含收件人。同一条评论的意图键只有一个,但它可能通知多个人;只按意图键去重会让第二个人收不到通知。
|
|
|
|
|
|
|
|
|
|
|
|
**失败只记日志。** 通知是派生副作用:写失败不改变"评论已发布"的结论,但必须留痕,否则"用户说没收到通知"无从排查。
|
|
|
|
|
|
|
|
|
|
|
|
### 5.2 `CreateMentions`:同批共享时间戳
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
|
|
|
|
|
|
if len(mentions) == 0 {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
now := time.Now()
|
|
|
|
|
|
rows := make([]notification.Notification, 0, len(mentions))
|
|
|
|
|
|
for _, m := range mentions {
|
|
|
|
|
|
rows = append(rows, notification.Notification{
|
|
|
|
|
|
...
|
|
|
|
|
|
CreatedAt: now,
|
|
|
|
|
|
DedupeKey: nilIfEmpty(m.DedupeKey),
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
return r.db.WithContext(ctx).
|
|
|
|
|
|
Clauses(clause.OnConflict{DoNothing: true}).
|
|
|
|
|
|
Create(&rows).Error
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
显式写 `CreatedAt` 而不依赖 `autoCreateTime`:`autoCreateTime` 只在字段为零值时才生效,逐行插入会拿到毫秒级不同的时间;同一批行共享一个时间戳,便于按"同一次评论"检索。
|
|
|
|
|
|
|
|
|
|
|
|
### 5.3 通知实体为什么独立成包
|
|
|
|
|
|
|
|
|
|
|
|
`backend/internal/notification/entity.go` 是两个写入方共用的唯一实体定义:
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
package notification
|
|
|
|
|
|
|
|
|
|
|
|
type Notification struct {
|
|
|
|
|
|
...
|
|
|
|
|
|
DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (Notification) TableName() string { return "notifications" }
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
依赖方向恒为 `worker → notification` 与 `video → notification`:
|
|
|
|
|
|
|
|
|
|
|
|
- `video` 不能 import `worker`(`worker` 已经 import `video`,会成环);
|
|
|
|
|
|
- 各自维护一份结构体又会让列标签悄悄漂移,而漂移不会报错,只会在 `AutoMigrate` 时试图改动生产列类型。
|
|
|
|
|
|
|
|
|
|
|
|
`TableName()` 默认也是 `notifications`,显式写出是为了避免有人把类型改名后表名跟着漂移——这张表有两个写入方,表名漂移的代价远大于多写一行。
|
|
|
|
|
|
|
|
|
|
|
|
`DedupeKey` 用 `*string` 的原因与评论的 `IdempotencyKey` 相同:`NULL` 才不参与唯一约束。
|
|
|
|
|
|
|
|
|
|
|
|
### 5.4 通知消费端的幂等
|
|
|
|
|
|
|
|
|
|
|
|
去重键在写入时生效,推送必须跟着"是否真的插入"走:只有 `RowsAffected > 0` 才 `hub.Push`。否则列表里只有一条通知,用户却收到两次 SSE。
|
|
|
|
|
|
|
|
|
|
|
|
## 6. 热度层:Redis 占位
|
|
|
|
|
|
|
2026-11-01 16:47:25 +08:00
|
|
|
|
> **本节描述的是已被替换的设计。** P0-5 之后热度不再有独立的写路径:`hot:applied:<intentKey>` 占位与 `UpdatePopularityCache` 已随 `popularityMQ` 一起删除,热榜增量改由"事务是否真的写入了"驱动(`ApplyHotDelta`),失败不回滚、可由 DB 重建。当前设计见 [`hot-ranking.md`](hot-ranking.md)。本节保留为决策记录,说明"为什么当初要占位"以及"占位与副作用同生共死"这条约束从哪来。
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
### 6.1 为什么用占位而不是计数器
|
|
|
|
|
|
|
|
|
|
|
|
热度写在 Redis(分钟窗口 ZSET),没有唯一索引可用。做法是先抢占位、再执行副作用:
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
marker := ""
|
|
|
|
|
|
if intentKey != "" {
|
|
|
|
|
|
marker = cache.Key("hot:applied:%s", intentKey)
|
|
|
|
|
|
claimed, err := cache.SetNX(opCtx, marker, []byte("1"), hotAppliedTTL)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
if !claimed {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
`!claimed` 是正常语义,不是错误:这条意图已经加过分,直接返回成功。
|
|
|
|
|
|
|
|
|
|
|
|
`SetNX` 的实现有两条约定:
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
|
|
|
|
|
|
if c == nil || c.rdb == nil {
|
|
|
|
|
|
return false, errors.New("redis client not initialized")
|
|
|
|
|
|
}
|
|
|
|
|
|
return c.rdb.SetNX(ctx, key, value, ttl).Result()
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
- **key 由调用方拼好**,本方法不加前缀。加前缀的时机必须与其他原语一致,否则同一个逻辑键会因调用路径不同变成两个物理键。
|
|
|
|
|
|
- **失败必须返回 error,不能返回 `(false, nil)`**。调用方用它判断"是否已生效",把 Redis 故障静默说成"已生效"会导致该次加分被永久跳过。
|
|
|
|
|
|
|
|
|
|
|
|
### 6.2 占位必须与副作用同生共死
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil {
|
|
|
|
|
|
if marker != "" {
|
|
|
|
|
|
if delErr := cache.Del(context.Background(), marker); delErr != nil {
|
|
|
|
|
|
log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return fmt.Errorf("hot cache: zincrby video=%d change=%d: %w", id, change, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
ZINCRBY 失败而占位留下,这条增量就被永久跳过——用户只会觉得"热度不动了",比重复加分更难发现。因此失败分支必须撤销占位。
|
|
|
|
|
|
|
|
|
|
|
|
撤销本身用 `context.Background()`:`opCtx` 已经超时或即将超时,用它撤销会让"撤销"这一步自己失败。
|
|
|
|
|
|
|
|
|
|
|
|
撤销也失败时只记日志,不改变返回值。人工可以按 `hot:applied:<K>` 清理——这是"宁可留下明确证据,也不假装成功"。
|
|
|
|
|
|
|
|
|
|
|
|
### 6.3 超时的边界
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
hotOpTimeout = 100 * time.Millisecond
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
它约束三次计数往返:`SetNX`、`ZINCRBY`、`EXPIRE`。
|
|
|
|
|
|
|
|
|
|
|
|
三次 `Del`(详情缓存、实体缓存、撤销占位)都用 `context.Background()`,不受它约束。如果把删缓存也算进预算,Redis 一抖动就会让整条热度消息失败并触发重投——而删缓存失败最多让详情页多陈旧一个缓存 TTL,不值得让消息重投。
|
|
|
|
|
|
|
|
|
|
|
|
`EXPIRE` 失败只记日志:窗口已经写好,缺过期时间只是键长期驻留,不影响正确性。
|
|
|
|
|
|
|
|
|
|
|
|
### 6.4 两个 TTL
|
|
|
|
|
|
|
|
|
|
|
|
| 常量 | 值 | 理由 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| `hotAppliedTTL` | 2 小时 | 只需覆盖"同一事件的重复投递窗口"(重试 + 停泊重放 + 客户端重试);2 小时远大于该窗口,同时把键数量限制在可估算的量级 |
|
|
|
|
|
|
| `hotWindowTTL` | 2 小时 | 热榜只需最近若干窗口,留 2 小时是为了跨窗口查询与事后核对仍然可读 |
|
|
|
|
|
|
|
|
|
|
|
|
### 6.5 空键为什么不去重
|
|
|
|
|
|
|
|
|
|
|
|
`intentKey == ""` 时整段占位逻辑被跳过,直接加分。调用方(点赞兜底)已经保证"只有事件发不出去才走到这里",在这里再去重会把真实增量吞掉。
|
|
|
|
|
|
|
|
|
|
|
|
## 7. 点赞路径:一个键喂两条事件
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
// 一条意图键同时喂给"点赞事件"和"热度事件"
|
|
|
|
|
|
intentKey, err := NewIntentKey()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
likeEnqueued := false
|
|
|
|
|
|
popEnqueued := false
|
|
|
|
|
|
if s.likeMQ != nil {
|
|
|
|
|
|
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
|
|
|
|
|
|
likeEnqueued = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if s.popularityMQ != nil {
|
|
|
|
|
|
if err := s.popularityMQ.Update(ctx, like.VideoID, 1, intentKey); err == nil {
|
|
|
|
|
|
popEnqueued = true
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
点赞行本身有 `idx_like_video_account` 唯一索引 + `LikeIgnoreDuplicate`,幂等由数据库保证;热度那条轨用同一个键去抢 Redis 占位。两条消息重复投递时,各自的消费端都能识别。
|
|
|
|
|
|
|
|
|
|
|
|
**兜底必须拆成两个独立判断:**
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if !likeEnqueued {
|
|
|
|
|
|
// 直写:插 likes + likes_count + popularity
|
|
|
|
|
|
}
|
|
|
|
|
|
if !popEnqueued {
|
|
|
|
|
|
// 只更新热榜缓存
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
不能写成"两个都成功才 return,否则进同一个兜底"。旧写法的问题是:**点赞已入队 + 热度发布失败**时会再插一次 `likes`,撞 `idx_like_video_account` 的 1062,接口返回 500,而用户其实已经点赞成功;更糟的是 `IsLiked` 之后会告诉用户"你已经点过赞了"。
|
|
|
|
|
|
|
|
|
|
|
|
热度归热度,点赞归点赞——两条轨各自独立降级。
|
|
|
|
|
|
|
|
|
|
|
|
## 8. 消费端
|
|
|
|
|
|
|
|
|
|
|
|
### 8.1 事件字段到实体字段
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
if evt.EventID != "" {
|
|
|
|
|
|
key := evt.EventID
|
|
|
|
|
|
c.IdempotencyKey = &key
|
|
|
|
|
|
}
|
|
|
|
|
|
created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1)
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
`event_id` 就是"这次用户意图"的键。API 侧若已经兜底直写过,这次插入会命中唯一索引,`created=false`,热度不能再加一次。
|
|
|
|
|
|
|
|
|
|
|
|
`evt.EventID == ""` 时不设键:插入一行 `NULL` 键的评论,与旧行为一致,不会把不同事件判成同一条。
|
|
|
|
|
|
|
|
|
|
|
|
### 8.2 坏消息与空操作的区别
|
|
|
|
|
|
|
|
|
|
|
|
```go
|
|
|
|
|
|
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
if !ok {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
视频已被删除时返回 `nil`:没有可落评论的地方,但"处理完了"不等于"处理失败"。若返回 error,消息会在重试队列里空转直到停泊。
|
|
|
|
|
|
|
|
|
|
|
|
同一原则适用于:
|
|
|
|
|
|
|
|
|
|
|
|
| 情况 | 返回 | 原因 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| 视频不存在 | `nil` | 处理完了 |
|
|
|
|
|
|
| `event_id` 为空 | 正常插入 | 旧客户端行为 |
|
|
|
|
|
|
| 重复删除(`deleted=false`) | `nil` | 空操作 |
|
|
|
|
|
|
| 事件解析失败 / 字段非法 / 未知 action | `rabbitmq.Permanent` | 重投也不会成功 |
|
|
|
|
|
|
|
|
|
|
|
|
## 9. 失败矩阵
|
|
|
|
|
|
|
|
|
|
|
|
每种失败下,"评论 / 热度 / 通知"三者的结果:
|
|
|
|
|
|
|
|
|
|
|
|
| 失败点 | 评论 | 热度 | 通知 | 用户看到 |
|
|
|
|
|
|
|---|---|---|---|---|
|
|
|
|
|
|
| 正常 | 1 行(worker 写) | 队列 + Redis | 1 条 | 200 |
|
|
|
|
|
|
| 评论发布失败 | 1 行(API 直写) | 队列 + Redis | 1 条 | 200 |
|
|
|
|
|
|
| 评论发布失败 + 消息其实已入队 | 1 行(唯一索引吸收) | 只加一次 | 1 条 | 200 |
|
|
|
|
|
|
| 热度发布失败 | 1 行 | 只 Redis(直写缓存) | 1 条 | 200 |
|
|
|
|
|
|
| 两条都失败 | 1 行 | 只 Redis | 1 条 | 200 |
|
|
|
|
|
|
| Redis 加分失败 | 1 行 | 0 | 1 条 | 200(热度降级) |
|
|
|
|
|
|
| 客户端重试(同键) | 1 行 | 一次 | 1 条 | 200 |
|
|
|
|
|
|
| 客户端重试(新键) | 2 行 | 两次 | 2 条 | 200(这是两次意图) |
|
|
|
|
|
|
|
|
|
|
|
|
最后一行是有意的:用户改了内容再发,就是新意图。用内容哈希去重会误伤"用户真的想再发一条"的合法行为。
|
|
|
|
|
|
|
|
|
|
|
|
## 10. 接口分层与测试
|
|
|
|
|
|
|
|
|
|
|
|
四个接口的规模:
|
|
|
|
|
|
|
|
|
|
|
|
| 接口 | 方法数 | 生产代码 | 测试替身 |
|
|
|
|
|
|
|---|---|---|---|
|
|
|
|
|
|
| `CommentStore` | 7 | 接口声明 | ~60 行 |
|
|
|
|
|
|
| `CommentPublisher` | 2 | 接口声明 | ~15 行 |
|
|
|
|
|
|
| `PopularityPublisher` | 1 | 接口声明 | ~10 行 |
|
|
|
|
|
|
| `videoExister` | 1 | 接口声明 | ~5 行 |
|
|
|
|
|
|
|
|
|
|
|
|
`CommentStore` 的 7 个方法正好等于 `CommentService` 实际用到的 7 个,没有预留。
|
|
|
|
|
|
|
|
|
|
|
|
它们换来的覆盖:
|
|
|
|
|
|
|
|
|
|
|
|
- `TestCommentService_Publish_BothEnqueued_SkipsLocalWrite` —— 入队成功时不直写
|
|
|
|
|
|
- `TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey` —— 兜底与事件同键
|
|
|
|
|
|
- `TestCommentService_Publish_PopularityPublishFails_AppliesHotCacheOnce`
|
|
|
|
|
|
- `TestCommentService_Publish_RepeatSameIntent_DoesNotError`
|
|
|
|
|
|
- `TestCommentService_Publish_InvalidRequestID` —— 400 而非 500
|
|
|
|
|
|
- `TestCommentService_NotifyMentions_DedupeKeyBoundToIntent`
|
|
|
|
|
|
|
|
|
|
|
|
这些用例全部不需要 MySQL 与 broker。
|
|
|
|
|
|
|
|
|
|
|
|
## 11. 数据库约束的护栏
|
|
|
|
|
|
|
|
|
|
|
|
集成测试用真实 MySQL 验证"约束真的存在":
|
|
|
|
|
|
|
|
|
|
|
|
| 用例 | 断言 |
|
|
|
|
|
|
|---|---|
|
|
|
|
|
|
| `TestP0_4_DuplicateInsertReportsZeroRows` | 同键插两次:第二次 `created=false`,评论 1 行,popularity 1 |
|
|
|
|
|
|
| `TestP0_4_ConcurrentInsertSingleRow` | 8 个 goroutine 并发:只有 1 个 `created=true` |
|
|
|
|
|
|
| `TestP0_4_LegacyNullKeysCoexist` | 3 条 `NULL` 键共存 |
|
|
|
|
|
|
| `TestP0_4_MentionNotificationDedupe` | 同 `DedupeKey` 写两次只有 1 行 |
|
|
|
|
|
|
| `TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow` | 事件投递两次:评论 1 行,popularity 1 |
|
|
|
|
|
|
| `TestCommentWorker_ApplyDelete_DuplicateIsNoop` | 删除投递两次:热度只回退一次 |
|
|
|
|
|
|
|
|
|
|
|
|
集成测试的 DSN 必须显式检查不含 `clientFoundRows`,否则第 1 条会通过、第 5 条会失败,而失败原因看起来像业务 bug。
|
|
|
|
|
|
|
|
|
|
|
|
## 12. 可观测性
|
|
|
|
|
|
|
|
|
|
|
|
### 12.1 日志字段
|
|
|
|
|
|
|
|
|
|
|
|
| 字段 | 出现位置 | 用途 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| `intent_key=<K>` | API 与 Worker | 串起一次意图的全链路 |
|
|
|
|
|
|
| `stage=<name>` | API | 区分阶段:`comment.publish`、`mention.lookup`、`mention.create` |
|
|
|
|
|
|
| `dedupe=hit/miss` | API 兜底、Worker、通知 | 判重是否命中 |
|
|
|
|
|
|
| `author_id` / `video_id` / `event_id` | 两侧 | 定位具体对象 |
|
|
|
|
|
|
|
|
|
|
|
|
排查"用户说没看到评论":
|
|
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
grep intent_key=<K> # 有没有走到兜底、有没有 dedupe=hit
|
|
|
|
|
|
grep 'dedupe=hit' # 判重命中率,用来估算"假失败"的真实比例
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
### 12.2 SQL 校验
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
|
|
|
|
|
```sql
|
2026-10-31 00:03:52 +08:00
|
|
|
|
-- 同一意图不应有多行
|
|
|
|
|
|
SELECT author_id, idempotency_key, COUNT(*) FROM comments
|
|
|
|
|
|
WHERE idempotency_key IS NOT NULL
|
|
|
|
|
|
GROUP BY author_id, idempotency_key HAVING COUNT(*) > 1;
|
|
|
|
|
|
|
|
|
|
|
|
-- 同一意图对同一收件人不应有多条通知
|
|
|
|
|
|
SELECT dedupe_key, COUNT(*) FROM notifications
|
|
|
|
|
|
WHERE dedupe_key IS NOT NULL
|
|
|
|
|
|
GROUP BY dedupe_key HAVING COUNT(*) > 1;
|
|
|
|
|
|
|
|
|
|
|
|
-- 索引确实存在
|
|
|
|
|
|
SHOW INDEX FROM comments WHERE Key_name = 'uk_comments_author_key';
|
2026-10-30 23:48:47 +08:00
|
|
|
|
SHOW INDEX FROM notifications WHERE Key_name = 'uk_notifications_dedupe';
|
|
|
|
|
|
```
|
|
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
两条分组查询返回空,说明判重在工作;返回非空则说明有人绕过写入口直接插库。
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
## 13. 代码地图
|
2026-10-30 23:48:47 +08:00
|
|
|
|
|
2026-10-31 00:03:52 +08:00
|
|
|
|
| 文件 | 职责 | 关键符号 |
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
| `backend/internal/video/idempotency.go` | 键的生成、解析、校验;通知去重键 | `NewIntentKey`、`ResolveIntentKey`、`NotificationDedupeKey` |
|
|
|
|
|
|
| `backend/internal/video/comment_entity.go` | 唯一索引声明;请求体字段 | `Comment.IdempotencyKey`、`PublishCommentRequest.RequestID` |
|
|
|
|
|
|
| `backend/internal/video/comment_store.go` | 服务层依赖的窄接口 | `CommentStore`、`Mention`、`nilIfEmpty` |
|
|
|
|
|
|
| `backend/internal/video/comment_repo.go` | 单事务"插入或跳过 + 热度" | `CreateIdempotentWithPopularity`、`DeleteByID`、`CreateMentions` |
|
|
|
|
|
|
| `backend/internal/video/comment_service.go` | 编排两条路径、生成通知 | `Publish`、`notifyMentions`、`logIntent` |
|
|
|
|
|
|
| `backend/internal/video/comment_handler.go` | 接收并回显 `request_id` | `PublishComment` |
|
|
|
|
|
|
| `backend/internal/video/popularity_cache.go` | 热度占位、撤销、窗口计数 | `UpdatePopularityCache` |
|
|
|
|
|
|
| `backend/internal/video/like_service.go` | 一个键喂两条事件 | `Like`、`Unlike` |
|
|
|
|
|
|
| `backend/internal/middleware/redis/cache.go` | `SETNX` 原语 | `SetNX` |
|
|
|
|
|
|
| `backend/internal/middleware/rabbitmq/commentMQ.go` | 事件携带意图键 | `Publish`、`Delete` |
|
|
|
|
|
|
| `backend/internal/worker/commentworker.go` | 消费端用同一个键写库 | `applyPublish`、`applyDelete` |
|
|
|
|
|
|
| `backend/internal/worker/notificationworker.go` | 通知去重与推送 | `persist` |
|
|
|
|
|
|
| `backend/internal/notification/entity.go` | `notifications` 表唯一实体 | `Notification` |
|
|
|
|
|
|
|
|
|
|
|
|
## 14. 这套设计不做的事
|
|
|
|
|
|
|
|
|
|
|
|
- **不做全局 `processed_events` 台账。** 先记台账再执行会丢写,后记会重复写,同事务记录则等价于目标表唯一索引,且管不到 Redis。
|
|
|
|
|
|
- **不用内容哈希做唯一键。** "好看"发两次是合法行为,哈希会误伤;哈希碰撞还会把两条不同评论合成一条。
|
|
|
|
|
|
- **不在判重命中时返回 409。** 重复是正常语义,客户端应当把它显示成成功。
|
|
|
|
|
|
- **不清理存量重复数据。** 唯一索引只能约束新增;存量重复需要人工评估后再删,删除时必须同步回退热度。
|
|
|
|
|
|
- **不把删除热度回退做成无条件动作。** 门控点是 `DeleteByID` 的 `deleted bool`。
|
|
|
|
|
|
|
|
|
|
|
|
## 15. 一句话总结
|
|
|
|
|
|
|
|
|
|
|
|
一次意图一个键;键写进唯一索引;判重与副作用在同一条 SQL 或同一个 `SETNX` 里完成;所有副作用都以"这次是否真的执行了"为门控。
|