背景叙述与历史取舍已写进 `docs/design/hot-ranking.md`,从源码删除。 只保留不变式与安全约束:`clientFoundRows` 禁令、唯一索引判重、 成员补零的排序约定、快照用 `RENAMENX` 只建一次、`EXPIRE` 失败即删键。 `video_service.go` 的 `NewVideoService` 注释原本复述已删方法的来历,一并收敛。 `zset.go` 的 `ZUnionStore` 与 `RenameNX` 注释各压到四行以内。 验证:go build ./... 通过。 验证:go vet ./... 通过。 验证:go test -count=1 ./... 全绿(本机无 cgo,未跑 -race)。 验证:go test -tags integration -p 1 -count=1 ./internal/feed/ ./internal/video/ ./internal/worker/ 全绿。
201 lines
4.7 KiB
Go
201 lines
4.7 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 不涉及热度写入:likes_count / popularity 只由点赞与评论的
|
||
// 业务事务维护。
|
||
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
|
||
}
|