P0-4 的写层基础:给每次"用户想发一条评论"一个稳定的意图键,并让判重 与写入成为同一条 SQL 的同一个事务。 - comments 加 idempotency_key,与 author_id 组成唯一索引 uk_comments_author_key。用 *string 而不是 string:MySQL 不约束 NULL, 多条无键评论才能共存;空串会互相撞键。 - CreateIdempotentWithPopularity 在一个事务里完成"插入评论 + 首次插入时 视频热度 +1"。重复写入静默返回 created=false,不报错、不覆盖、不再加 热度。判重交给数据库唯一索引,因此不存在"先 SELECT 再 INSERT"的窗口 ——那个窗口正是 MQ 假失败后兜底直写与 worker 稍后消费的交错点。 - DeleteByID 汇报是否真的删掉了一行,作为删除侧热度回退的门控点 (P2-20)。删除事件的重复投递与新增同样会把热度减两次。 - CreateMentions 按 dedupe_key 幂等写入提及通知,并显式写 CreatedAt (P2-16 ①);FindAccountIDs 用一次 username IN (?) 替换逐个查询。 - CommentStore 接口把"判重与写入必须同事务"这条约束变成显式的名字。 集成测试(-tags integration,需要 MYSQL_TEST_DSN)覆盖:重复插入报告 0 行且热度只加一次、8 并发只有 1 个 created、多条 NULL 键共存、提及通知 去重且 CreatedAt 非零、用户名批量解析。
47 lines
1.8 KiB
Go
47 lines
1.8 KiB
Go
package video
|
||
|
||
import "time"
|
||
|
||
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 是"这次发评论的意图"的稳定标识(P0-4)。
|
||
//
|
||
// 与 AuthorID 组成唯一索引 uk_comments_author_key:同一次用户意图
|
||
// 无论被写入几次(MQ 假失败后的 DB 兜底、worker 重复投递、客户端
|
||
// 重试),在数据库里都只会留下一行。
|
||
//
|
||
// 必须是指针:MySQL 的唯一索引不约束 NULL,多个 NULL 可以共存。
|
||
// 若用 string + 空串,存量行与"没带 request_id"的行会全部撞在
|
||
// 同一个 '' 上,第二条无键评论就会被判成重复。
|
||
//
|
||
// json:"-" 让它不出现在任何 API 响应里:它是去重机制的内部标识,
|
||
// 不是用户可见的数据。
|
||
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
|
||
}
|
||
|
||
type PublishCommentRequest struct {
|
||
VideoID uint `json:"video_id"`
|
||
Content string `json:"content"`
|
||
|
||
// RequestID 由客户端为"一次发送动作"生成,重试时复用同一个值。
|
||
//
|
||
// 为空时服务端会生成一个(单次请求内仍然幂等,但客户端重试无法被识别)。
|
||
// 校验规则见 idempotency.go:8–64 个 [0-9a-zA-Z_-] 字符,非法值返回 400
|
||
// 而不是静默截断或忽略。
|
||
RequestID string `json:"request_id"`
|
||
}
|
||
|
||
type DeleteCommentRequest struct {
|
||
CommentID uint `json:"comment_id"`
|
||
}
|
||
|
||
type GetAllCommentsRequest struct {
|
||
VideoID uint `json:"video_id"`
|
||
}
|