热度有两个写入者(PopularityWorker 与兜底直写)和三份实现,其中 VideoService.UpdatePopularity 是死代码且漏删 video:entity 缓存。这里 收敛成一条轨,并让"加过分"这件事可以判重。 - popularity_cache: UpdatePopularityCache 改成 5 参数并返回 error, 用 redis SETNX 占位 hot:applied:<意图键> 实现幂等;ZINCRBY 失败必须 撤销占位再上抛(占位留在失败路径上会让增量被永久跳过);三次 Del 是 best-effort,不受 opCtx 约束。返回 error 同时修掉 P0-3 的 N2—— 原来三条路径全返回 nil,消费端的 Nack/重试/sleep 全是死代码。 - popularityMQ.Update / likeMQ.Like/Unlike 增加 intentKey 入参,写进 event_id,让点赞事件与热度事件共享一次判重身份。 - like_service: 兜底拆成两个独立的 if(!likeEnqueued 写 DB、 !popEnqueued 写热榜)。旧代码"两个都成功才 return"会在"点赞已入队 + 热度发布失败"时再插一次 likes,撞唯一索引返回 500,而点赞其实成功了。 - 删除 VideoService.UpdatePopularity 及其 popularityMQ 字段与构造参数 (router.go 是唯一调用点)。 行为变更:点赞在热度发布失败时不再返回 500。热度是展示数据,失败只降级 记日志,不回滚已经成立的点赞。
203 lines
4.9 KiB
Go
203 lines
4.9 KiB
Go
package video
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"strings"
|
||
"time"
|
||
|
||
"feedsystem_video_go/internal/apierror"
|
||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
type VideoService struct {
|
||
repo *VideoRepository
|
||
cache *rediscache.Client
|
||
cacheTTL time.Duration
|
||
}
|
||
|
||
// NewVideoService 不再接收 popularityMQ:热度写入只有两个入口——
|
||
// PopularityWorker(异步)与 LikeService/CommentService 的兜底路径,
|
||
// 视频服务从来不直接改热度。原来这里挂着一个没人调用的 UpdatePopularity,
|
||
// 它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
|
||
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
|
||
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
|
||
}
|
||
|
||
func (vs *VideoService) Publish(ctx context.Context, video *Video) error {
|
||
if video == nil {
|
||
return errors.New("video is nil")
|
||
}
|
||
video.Title = strings.TrimSpace(video.Title)
|
||
video.PlayURL = strings.TrimSpace(video.PlayURL)
|
||
video.CoverURL = strings.TrimSpace(video.CoverURL)
|
||
|
||
if video.Title == "" {
|
||
return errors.New("title is required")
|
||
}
|
||
if video.PlayURL == "" {
|
||
return errors.New("play url is required")
|
||
}
|
||
if video.CoverURL == "" {
|
||
return errors.New("cover url is required")
|
||
}
|
||
|
||
//事务保证视频写入库和消息写入本地消息表的一致性
|
||
err := vs.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||
if err := tx.Create(video).Error; err != nil {
|
||
return err
|
||
}
|
||
|
||
msg := OutboxMsg{
|
||
VideoID: video.ID,
|
||
EventType: "video_published",
|
||
Status: "pending",
|
||
CreateTime: video.CreateTime,
|
||
}
|
||
|
||
if err := tx.Create(&msg).Error; err != nil {
|
||
return err
|
||
}
|
||
|
||
tags := ExtractTags(video.Title + " " + video.Description)
|
||
for _, tagName := range tags {
|
||
var tag Tag
|
||
if err := tx.Where("name = ?", tagName).FirstOrCreate(&tag, Tag{Name: tagName}).Error; err != nil {
|
||
return err
|
||
}
|
||
if err := tx.Create(&VideoTag{VideoID: video.ID, TagID: tag.ID}).Error; err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return nil
|
||
})
|
||
return err
|
||
|
||
}
|
||
|
||
func (vs *VideoService) Delete(ctx context.Context, id uint, authorID uint) error {
|
||
video, err := vs.repo.GetByID(ctx, id)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if video == nil {
|
||
return errors.New("video not found")
|
||
}
|
||
if video.AuthorID != authorID {
|
||
return apierror.ErrUnauthorized
|
||
}
|
||
if err := vs.repo.DeleteVideo(ctx, id); err != nil {
|
||
return err
|
||
}
|
||
if vs.cache != nil {
|
||
cacheKey := vs.cache.Key("video:detail:id=%d", id)
|
||
_ = vs.cache.Del(context.Background(), cacheKey)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (vs *VideoService) ListByAuthorID(ctx context.Context, authorID uint) ([]Video, error) {
|
||
videos, err := vs.repo.ListByAuthorID(ctx, int64(authorID))
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return videos, nil
|
||
}
|
||
|
||
func (vs *VideoService) GetDetail(ctx context.Context, id uint) (*Video, error) {
|
||
cacheKey := vs.cache.Key("video:detail:id=%d", id)
|
||
|
||
getCached := func() (*Video, bool) {
|
||
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
defer cancel()
|
||
|
||
b, err := vs.cache.GetBytes(opCtx, cacheKey)
|
||
if err != nil {
|
||
return nil, false
|
||
}
|
||
var cached Video
|
||
if err := json.Unmarshal(b, &cached); err != nil {
|
||
return nil, false
|
||
}
|
||
return &cached, true
|
||
}
|
||
|
||
setCached := func(video *Video) {
|
||
b, err := json.Marshal(video)
|
||
if err != nil {
|
||
return
|
||
}
|
||
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
defer cancel()
|
||
_ = vs.cache.SetBytes(opCtx, cacheKey, b, vs.cacheTTL)
|
||
}
|
||
|
||
if vs.cache != nil {
|
||
if v, ok := getCached(); ok {
|
||
return v, nil
|
||
}
|
||
|
||
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
b, err := vs.cache.GetBytes(opCtx, cacheKey)
|
||
cancel()
|
||
if err == nil {
|
||
var cached Video
|
||
if err := json.Unmarshal(b, &cached); err == nil {
|
||
return &cached, nil
|
||
}
|
||
} else if rediscache.IsMiss(err) {
|
||
lockKey := "lock:" + cacheKey
|
||
|
||
lockCtx, lockCancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
token, locked, lockErr := vs.cache.Lock(lockCtx, lockKey, 2*time.Second)
|
||
lockCancel()
|
||
|
||
if lockErr == nil && locked {
|
||
defer func() { _ = vs.cache.Unlock(context.Background(), lockKey, token) }()
|
||
|
||
if v, ok := getCached(); ok {
|
||
return v, nil
|
||
}
|
||
|
||
video, err := vs.repo.GetByID(ctx, id)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
setCached(video)
|
||
return video, nil
|
||
}
|
||
|
||
// 没拿到锁:等待别人回填缓存
|
||
for i := 0; i < 5; i++ {
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
case <-time.After(20 * time.Millisecond):
|
||
}
|
||
if v, ok := getCached(); ok {
|
||
return v, nil
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
video, err := vs.repo.GetByID(ctx, id)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if vs.cache != nil {
|
||
setCached(video)
|
||
}
|
||
return video, nil
|
||
}
|
||
|
||
func (vs *VideoService) UpdateLikesCount(ctx context.Context, id uint, likesCount int64) error {
|
||
if err := vs.repo.UpdateLikesCount(ctx, id, likesCount); err != nil {
|
||
return err
|
||
}
|
||
return nil
|
||
}
|