Files
VLoop/backend/internal/video/video_service.go
huanghaosheng 1b47c9f027 refactor(video): 计数改由业务事务维护并删除热度第二条写路径
点赞与评论的计数只由业务事务写。ApplyLike、ApplyUnlike、CreateIdempotentWithPopularity 与 DeleteWithPopularity 各自在单事务内完成插行与计数。
热榜增量改为提交后的 best-effort 写。ApplyHotDelta 按行的 created_at 落分钟桶,写失败只记日志,DB 计数仍然正确。
删除 PopularityMQ 与 PopularityWorker。同一次互动因此只有一个写者,不再有两个门闩各自放行。
删除 hot:applied 占位键。判重改由 likes 的唯一索引与 uk_comments_author_key 负责。
DeleteWithPopularity 先读行再删行。评论删除因此回退热度,重复投递不再多减一次。
likes 与 comments 各加 (created_at, video_id) 覆盖索引,服务热榜窗口查询。
验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
2026-11-01 15:15:15 +08:00

203 lines
5.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 不涉及热度写入:likes_count / popularity 只由点赞与评论的
// 业务事务维护(LikeRepository.ApplyLike、CommentRepository.CreateIdempotentWithPopularity、
// DeleteWithPopularity),视频服务从来不直接改热度。原来这里挂着一个没人调用的
// 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
}