窗口右端改为上一个已闭合分钟。当前分钟仍在增长,不能当右端。 一个 as_of 的快照只建一次。ZUNIONSTORE 先写临时键,再用 RENAMENX 原子占位,抢不到的人读赢家。 空并集不再发布成快照。否则这个 as_of 在 TTL 内每次都会命中一张空表,却报告 snapshot_rebuilt=false。 快照 TTL 改为 1 小时。EXPIRE 失败时删掉 dest,避免它继承临时键的 1 分钟寿命而永远翻不到第 2 页。 NextOffset 按 len(members) 推进。视频被删除后 member 仍在,按存活视频数推进会重复读到已跳过的位置。 DB 回退改用 ListHotWindow 重算同一窗口。排序为 score DESC, video_id DESC,与 ZSET 一致。 窗口内无互动时返回 latest。这一支是终结页,NextOffset 为 0。 ZUnionStore 返回并集基数,供调用方判空。新增 RenameNX 包装方法。 删除旧游标字段与 latest_* 配对校验。请求只剩 limit、as_of、offset。 验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
718 lines
23 KiB
Go
718 lines
23 KiB
Go
package feed
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||
"feedsystem_video_go/internal/video"
|
||
"fmt"
|
||
"log"
|
||
"strconv"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/patrickmn/go-cache"
|
||
redis "github.com/redis/go-redis/v9"
|
||
"golang.org/x/sync/singleflight"
|
||
)
|
||
|
||
type FeedService struct {
|
||
repo *FeedRepository
|
||
likeRepo *video.LikeRepository
|
||
rediscache *rediscache.Client
|
||
localcache *cache.Cache
|
||
cacheTTL time.Duration
|
||
requestGroup singleflight.Group
|
||
}
|
||
|
||
type CachedFeedData struct {
|
||
PublicVideos []video.Video `json:"public_videos"`
|
||
}
|
||
|
||
func NewFeedService(repo *FeedRepository, likeRepo *video.LikeRepository, rediscache *rediscache.Client) *FeedService {
|
||
return &FeedService{repo: repo, likeRepo: likeRepo, rediscache: rediscache, localcache: cache.New(3*time.Second, 5*time.Second), cacheTTL: 24 * time.Hour}
|
||
}
|
||
|
||
// GetVideoByIDs 批量获取视频信息
|
||
// 采用 L1(本地缓存) -> L2(Redis) -> L3(MySQL) 三级架构
|
||
func (f *FeedService) GetVideoByIDs(ctx context.Context, videoIDs []uint) ([]*video.Video, error) {
|
||
if len(videoIDs) == 0 {
|
||
return []*video.Video{}, nil
|
||
}
|
||
|
||
videoMap := make(map[uint]*video.Video)
|
||
//L1:本地缓存
|
||
var missedL1 []uint
|
||
for _, id := range videoIDs {
|
||
cacheKey := f.rediscache.Key("video:entity:%d", id)
|
||
if f.localcache != nil {
|
||
if v, found := f.localcache.Get(cacheKey); found {
|
||
if data, ok := v.(video.Video); ok {
|
||
videoMap[id] = &data
|
||
continue
|
||
}
|
||
}
|
||
}
|
||
// 记录未命中的 ID,准备进入下一级缓存
|
||
missedL1 = append(missedL1, id)
|
||
}
|
||
|
||
if len(missedL1) == 0 {
|
||
return buildOrderedResult(videoIDs, videoMap), nil
|
||
}
|
||
|
||
//L2:redis
|
||
var missedL2 []uint
|
||
if len(missedL1) > 0 {
|
||
cacheKeys := make([]string, len(missedL1))
|
||
for i, id := range missedL1 {
|
||
cacheKeys[i] = f.rediscache.Key("video:entity:%d", id)
|
||
}
|
||
|
||
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
results, err := f.rediscache.MGet(cacheCtx, cacheKeys...)
|
||
cancel()
|
||
|
||
if err == nil {
|
||
for i, res := range results {
|
||
id := missedL1[i]
|
||
if res != nil {
|
||
if str, ok := res.(string); ok {
|
||
var v video.Video
|
||
if err := json.Unmarshal([]byte(str), &v); err == nil {
|
||
videoMap[id] = &v
|
||
// 回写更新 L1 本地缓存
|
||
if f.localcache != nil {
|
||
f.localcache.Set(cacheKeys[i], v, 5*time.Second)
|
||
}
|
||
continue
|
||
}
|
||
}
|
||
}
|
||
missedL2 = append(missedL2, id)
|
||
}
|
||
} else {
|
||
// 如果 Redis 挂了或者超时了,全部降级到 L3
|
||
missedL2 = missedL1
|
||
log.Printf("L2 Redis MGet 失败,全部降级到 MySQL: %v", err)
|
||
}
|
||
}
|
||
|
||
if len(missedL2) == 0 {
|
||
return buildOrderedResult(videoIDs, videoMap), nil
|
||
}
|
||
|
||
//L3:MySQL
|
||
var wg sync.WaitGroup
|
||
var mu sync.Mutex
|
||
for _, id := range missedL2 {
|
||
wg.Add(1)
|
||
go func(videoID uint) {
|
||
defer wg.Done()
|
||
|
||
// singleflight 防止缓存击穿
|
||
sfKey := f.rediscache.Key("sf:entity:%d", videoID)
|
||
|
||
v, err, _ := f.requestGroup.Do(sfKey, func() (interface{}, error) {
|
||
videoList, err := f.repo.GetByIDs(ctx, []uint{videoID})
|
||
|
||
if err != nil || len(videoList) == 0 {
|
||
return nil, err
|
||
}
|
||
|
||
safeCopy := *videoList[0]
|
||
cachekey := f.rediscache.Key("video:entity:%d", safeCopy.ID)
|
||
if b, err := json.Marshal(safeCopy); err == nil {
|
||
//异步回写redis
|
||
go func(k string, b []byte) {
|
||
setCtx, setCancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||
defer setCancel()
|
||
|
||
f.rediscache.SetBytes(setCtx, k, b, time.Hour)
|
||
}(cachekey, b)
|
||
}
|
||
return videoList[0], err
|
||
})
|
||
|
||
if err == nil && v != nil {
|
||
safeCopy := *(v.(*video.Video))
|
||
mu.Lock()
|
||
videoMap[id] = &safeCopy
|
||
mu.Unlock()
|
||
f.localcache.Set(f.rediscache.Key("video:entity:%d", safeCopy.ID), safeCopy, 5*time.Second)
|
||
}
|
||
}(id)
|
||
}
|
||
wg.Wait()
|
||
return buildOrderedResult(videoIDs, videoMap), nil
|
||
}
|
||
|
||
// 查询最新视频 (冷热分离 + 游标分页)
|
||
func (f *FeedService) ListLatest(ctx context.Context, limit int, latestBefore time.Time, viewerAccountID uint) (ListLatestResponse, error) {
|
||
if f.rediscache == nil {
|
||
return f.listLatestFromDB(ctx, limit, latestBefore, viewerAccountID)
|
||
}
|
||
|
||
// 获取 ZSET 中最老的一条数据
|
||
zsetTail, err := f.rediscache.ZRangeWithScores(ctx, f.rediscache.Key("feed:global_timeline"), 0, 0)
|
||
|
||
if err != nil {
|
||
return f.listLatestFromDB(ctx, limit, latestBefore, viewerAccountID)
|
||
}
|
||
|
||
isZsetEmpty := len(zsetTail) == 0
|
||
|
||
// ZSet 为空时尝试重建 ZSet
|
||
if isZsetEmpty {
|
||
//全局静态锁:无视所有用户的不同时间戳游标
|
||
sfKey := f.rediscache.Key("sf:fallback:global_timeline_rebuild")
|
||
|
||
v, err, _ := f.requestGroup.Do(sfKey, func() (interface{}, error) {
|
||
// 无视游标,直接去 MySQL 捞最新的 1000 条
|
||
dbVideos, err := f.repo.ListLatest(ctx, 1000, time.Time{})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(dbVideos) == 0 {
|
||
return "EMPTY_DB", nil // 防无限递归
|
||
}
|
||
|
||
// 重建 ZSET
|
||
bgCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||
defer cancel()
|
||
var zElements []redis.Z
|
||
for _, vid := range dbVideos {
|
||
zElements = append(zElements, redis.Z{
|
||
Score: float64(vid.CreateTime.UnixMilli()),
|
||
Member: fmt.Sprintf("%d", vid.ID),
|
||
})
|
||
}
|
||
f.rediscache.ZAdd(bgCtx, f.rediscache.Key("feed:global_timeline"), zElements...)
|
||
return "SUCCESS", nil
|
||
})
|
||
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
if v == "EMPTY_DB" {
|
||
return ListLatestResponse{HasMore: false}, nil
|
||
}
|
||
|
||
// 递归调用自己,让所有被阻塞的请求重新查一遍
|
||
return f.ListLatest(ctx, limit, latestBefore, viewerAccountID)
|
||
}
|
||
|
||
// watermark 是 ZSET 中最老的一条数据的时间戳; reqTime 是本次请求的时间戳(如果没有传 latestBefore,则使用当前时间)
|
||
watermark := int64(zsetTail[0].Score)
|
||
reqTime := time.Now().UnixMilli()
|
||
if !latestBefore.IsZero() {
|
||
reqTime = latestBefore.UnixMilli()
|
||
}
|
||
|
||
var baseVideos []*video.Video
|
||
|
||
if reqTime <= watermark {
|
||
//冷数据降级查库
|
||
|
||
// 针对个别用户的防并发(此时可以用时间戳做锁,因为冷尾流量极小)
|
||
sfKey := f.rediscache.Key("sf:cold:listLatest:%d:%d", limit, reqTime)
|
||
v, err, _ := f.requestGroup.Do(sfKey, func() (interface{}, error) {
|
||
return f.repo.ListLatest(ctx, limit, latestBefore)
|
||
})
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
baseVideos = v.([]*video.Video)
|
||
// 不回写 ZSET,防止冷数据污染热点时间线
|
||
|
||
} else {
|
||
// 热数据直接查redis
|
||
maxScore := "+inf"
|
||
if !latestBefore.IsZero() {
|
||
maxScore = fmt.Sprintf("%d", reqTime-1) // 防重复
|
||
}
|
||
|
||
videoIDsStr, err := f.rediscache.ZRevRangeByScore(
|
||
ctx,
|
||
f.rediscache.Key("feed:global_timeline"),
|
||
maxScore,
|
||
"-inf",
|
||
0,
|
||
int64(limit),
|
||
)
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
|
||
// 将字符串 ID 转换为 uint
|
||
var videoIDs []uint
|
||
for _, idStr := range videoIDsStr {
|
||
if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
|
||
videoIDs = append(videoIDs, uint(id))
|
||
}
|
||
}
|
||
|
||
if len(videoIDs) > 0 {
|
||
baseVideos, err = f.GetVideoByIDs(ctx, videoIDs)
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
}
|
||
|
||
// 刚好击穿了冷热边界,从数据库中再拉一些冷数据补齐
|
||
if len(baseVideos) < limit {
|
||
remainLimit := limit - len(baseVideos) // 计算还差几个
|
||
|
||
var coldCursor time.Time
|
||
if len(baseVideos) > 0 {
|
||
coldCursor = baseVideos[len(baseVideos)-1].CreateTime
|
||
} else {
|
||
coldCursor = latestBefore
|
||
}
|
||
|
||
sfKey := f.rediscache.Key("sf:stitch:listLatest:%d:%d", remainLimit, coldCursor.UnixMilli())
|
||
v, err, _ := f.requestGroup.Do(sfKey, func() (interface{}, error) {
|
||
return f.repo.ListLatest(ctx, remainLimit, coldCursor)
|
||
})
|
||
|
||
if err == nil {
|
||
coldVideos := v.([]*video.Video)
|
||
baseVideos = append(baseVideos, coldVideos...)
|
||
}
|
||
}
|
||
}
|
||
|
||
var nextTime int64
|
||
if len(baseVideos) > 0 {
|
||
// 将本页最后一条视频的时间作为下一次请求的游标
|
||
nextTime = baseVideos[len(baseVideos)-1].CreateTime.UnixMilli()
|
||
}
|
||
hasMore := len(baseVideos) == limit
|
||
|
||
feedVideos, err := f.buildFeedVideos(ctx, baseVideos, viewerAccountID)
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
|
||
return ListLatestResponse{
|
||
VideoList: feedVideos,
|
||
NextTime: nextTime,
|
||
HasMore: hasMore,
|
||
}, nil
|
||
}
|
||
|
||
func (f *FeedService) listLatestFromDB(ctx context.Context, limit int, latestBefore time.Time, viewerAccountID uint) (ListLatestResponse, error) {
|
||
videos, err := f.repo.ListLatest(ctx, limit, latestBefore)
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||
if err != nil {
|
||
return ListLatestResponse{}, err
|
||
}
|
||
var nextTime int64
|
||
if len(videos) > 0 {
|
||
nextTime = videos[len(videos)-1].CreateTime.UnixMilli()
|
||
}
|
||
return ListLatestResponse{
|
||
VideoList: feedVideos,
|
||
NextTime: nextTime,
|
||
HasMore: len(videos) == limit,
|
||
}, nil
|
||
}
|
||
|
||
// 按照点赞数查询视频
|
||
func (f *FeedService) ListLikesCount(ctx context.Context, limit int, cursor *LikesCountCursor, viewerAccountID uint) (ListLikesCountResponse, error) {
|
||
videos, err := f.repo.ListLikesCountWithCursor(ctx, limit, cursor)
|
||
if err != nil {
|
||
return ListLikesCountResponse{}, err
|
||
}
|
||
hasMore := len(videos) == limit
|
||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||
if err != nil {
|
||
return ListLikesCountResponse{}, err
|
||
}
|
||
resp := ListLikesCountResponse{
|
||
VideoList: feedVideos,
|
||
HasMore: hasMore,
|
||
}
|
||
if len(videos) > 0 {
|
||
last := videos[len(videos)-1]
|
||
nextLikesCountBefore := last.LikesCount
|
||
nextIDBefore := last.ID
|
||
resp.NextLikesCountBefore = &nextLikesCountBefore
|
||
resp.NextIDBefore = &nextIDBefore
|
||
}
|
||
return resp, nil
|
||
}
|
||
|
||
// 按照关注列表查询视频
|
||
func (f *FeedService) ListByFollowing(ctx context.Context, limit int, latestBefore time.Time, viewerAccountID uint) (ListByFollowingResponse, error) {
|
||
doListByFollowingFromDB := func() (ListByFollowingResponse, error) {
|
||
videos, err := f.repo.ListByFollowing(ctx, limit, viewerAccountID, latestBefore)
|
||
if err != nil {
|
||
return ListByFollowingResponse{}, err
|
||
}
|
||
var nextTime int64
|
||
if len(videos) > 0 {
|
||
nextTime = videos[len(videos)-1].CreateTime.Unix()
|
||
} else {
|
||
nextTime = 0
|
||
}
|
||
hasMore := len(videos) == limit
|
||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||
if err != nil {
|
||
return ListByFollowingResponse{}, err
|
||
}
|
||
resp := ListByFollowingResponse{
|
||
VideoList: feedVideos,
|
||
NextTime: nextTime,
|
||
HasMore: hasMore,
|
||
}
|
||
return resp, nil
|
||
}
|
||
var cacheKey string
|
||
if viewerAccountID != 0 && f.rediscache != nil {
|
||
before := int64(0)
|
||
if !latestBefore.IsZero() {
|
||
before = latestBefore.Unix()
|
||
}
|
||
cacheKey = f.rediscache.Key("feed:listByFollowing:limit=%d:accountID=%d:before=%d", limit, viewerAccountID, before)
|
||
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
defer cancel()
|
||
|
||
b, err := f.rediscache.GetBytes(cacheCtx, cacheKey)
|
||
if err == nil {
|
||
var cached ListByFollowingResponse
|
||
if err := json.Unmarshal(b, &cached); err == nil {
|
||
return cached, nil
|
||
}
|
||
} else if rediscache.IsMiss(err) { // 缓存未命中
|
||
lockKey := "lock:" + cacheKey
|
||
// 缓存未命中,尝试加锁
|
||
token, locked, _ := f.rediscache.Lock(cacheCtx, lockKey, 500*time.Millisecond)
|
||
if locked {
|
||
defer func() { _ = f.rediscache.Unlock(context.Background(), lockKey, token) }()
|
||
// Double check:再次检查缓存是否被其他请求回写
|
||
if b, err := f.rediscache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||
var cached ListByFollowingResponse
|
||
if err := json.Unmarshal(b, &cached); err == nil {
|
||
return cached, nil
|
||
}
|
||
} else { // 缓存未命中,从数据库中查询
|
||
resp, err := doListByFollowingFromDB()
|
||
if err != nil {
|
||
return ListByFollowingResponse{}, err
|
||
}
|
||
if b, err := json.Marshal(resp); err == nil {
|
||
_ = f.rediscache.SetBytes(cacheCtx, cacheKey, b, f.cacheTTL)
|
||
}
|
||
return resp, nil
|
||
}
|
||
} else { // 加锁失败,循环等待缓存被其他请求回写
|
||
for i := 0; i < 5; i++ {
|
||
time.Sleep(20 * time.Millisecond)
|
||
if b, err := f.rediscache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||
var cached ListByFollowingResponse
|
||
if err := json.Unmarshal(b, &cached); err == nil {
|
||
return cached, nil
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 缓存未命中或 Redis 不可用,降级成数据库查询
|
||
resp, err := doListByFollowingFromDB()
|
||
if err != nil {
|
||
return ListByFollowingResponse{}, err
|
||
}
|
||
if cacheKey != "" { // 缓存回写
|
||
if b, err := json.Marshal(resp); err == nil {
|
||
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||
defer cancel()
|
||
_ = f.rediscache.SetBytes(cacheCtx, cacheKey, b, f.cacheTTL)
|
||
}
|
||
}
|
||
return resp, nil
|
||
}
|
||
|
||
// hotSnapshotTTL 是一个 as_of 的快照寿命。
|
||
//
|
||
// 它要覆盖一次浏览会话,也要覆盖被驱逐后的重建窗口。1 小时与
|
||
// video.HotWindowTTL 同量级:任何时刻最多 60 个不同的 as_of 活着,
|
||
// 因此内存上界可算。
|
||
const hotSnapshotTTL = time.Hour
|
||
|
||
// lastClosedMinute 返回上一个已闭合的分钟(UTC)。
|
||
//
|
||
// 当前这一分钟仍在增长,永远不能当窗口右端:否则同一个 as_of 的榜会
|
||
// 在用户翻页的过程中自己变大,分页随之错位(N6)。
|
||
func lastClosedMinute(now time.Time) time.Time {
|
||
return now.UTC().Truncate(time.Minute).Add(-time.Minute)
|
||
}
|
||
|
||
// hotWindowBounds 返回 [asOf-59m, asOf+1m),正好覆盖 60 个分钟桶。
|
||
func hotWindowBounds(asOf time.Time) (from, to time.Time) {
|
||
from = asOf.Add(-time.Duration(video.HotWindowMinutes-1) * time.Minute)
|
||
to = asOf.Add(time.Minute)
|
||
return
|
||
}
|
||
|
||
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint) (ListByPopularityResponse, error) {
|
||
asOf := lastClosedMinute(time.Now())
|
||
if reqAsOf > 0 {
|
||
want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)
|
||
// 只接受"比当前分钟更早、且还在快照 TTL 内"的 as_of:
|
||
// - 未来或当前分钟:窗口还在增长(N6);
|
||
// - 比 TTL 更老:快照早已过期,重建出来是另一个榜,不能再用同一个
|
||
// as_of 交回去(客户端据响应 as_of 的变化重置分页)。
|
||
if want.Before(asOf) && time.Since(want) <= hotSnapshotTTL {
|
||
asOf = want
|
||
}
|
||
}
|
||
|
||
if f.rediscache != nil {
|
||
resp, ok, err := f.listByHotWindowRedis(ctx, limit, offset, asOf, viewerAccountID)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
if ok {
|
||
return resp, nil
|
||
}
|
||
}
|
||
return f.listByHotWindowDB(ctx, limit, offset, asOf, viewerAccountID)
|
||
}
|
||
|
||
func (f *FeedService) listByHotWindowRedis(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, bool, error) {
|
||
from, _ := hotWindowBounds(asOf)
|
||
keys := make([]string, 0, video.HotWindowMinutes)
|
||
for t := from; !t.After(asOf); t = t.Add(time.Minute) {
|
||
keys = append(keys, f.rediscache.Key("hot:video:1m:%s", video.HotBucket(t)))
|
||
}
|
||
dest := f.rediscache.Key("hot:video:merge:1m:%s", video.HotBucket(asOf))
|
||
|
||
// 120ms 覆盖下面 5 次往返(含 ZUNIONSTORE 60 个键)。它比写入侧的
|
||
// hotOpTimeout 宽,但按读 P99 标定:超时一律落 DB 回退,而那条路是最贵的
|
||
// 查询,所以超时率要能观测。
|
||
opCtx, cancel := context.WithTimeout(ctx, 120*time.Millisecond)
|
||
defer cancel()
|
||
exists, err := f.rediscache.Exists(opCtx, dest)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, nil // Redis 抖动:交给 DB 窗口
|
||
}
|
||
if !exists {
|
||
// 快照只建一次。直接 ZUnionStore 到 dest 会覆盖已有内容:并发两个请求
|
||
// 时,后到的那个会把先到的快照换掉,"同一会话同一个榜"就没了。
|
||
// 先算到临时键,再用 RENAMENX 原子占位:抢到的人赢,没抢到的人丢掉
|
||
// 临时键,继续读已经存在的 dest。
|
||
tmp := dest + ":build:" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||
n, err := f.rediscache.ZUnionStore(opCtx, tmp, keys, "SUM")
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, nil
|
||
}
|
||
if n == 0 {
|
||
// ZUNIONSTORE 在没有成员时仍会创建一张空表。若把它发布成快照,
|
||
// 这个 as_of 在 hotSnapshotTTL 内每次都会命中"存在的空快照",
|
||
// 于是每次都落 DB,却又报告 snapshot_rebuilt=false——
|
||
// "真的空榜"与"快照丢了"从此分不开。丢掉临时键,交给 DB 路径判定。
|
||
_ = f.rediscache.Del(opCtx, tmp)
|
||
return ListByPopularityResponse{}, false, nil
|
||
}
|
||
// 临时键也给一个短 TTL:进程若在 ZUnionStore 与 RENAMENX 之间崩溃,
|
||
// 没有 TTL 的 tmp 会永久留下。RENAMENX 会把 TTL 一起带给 dest,
|
||
// 下一行的 Expire 再把它改成快照寿命。
|
||
if err := f.rediscache.Expire(opCtx, tmp, time.Minute); err != nil {
|
||
log.Printf("feed: expire hot snapshot tmp %s failed (non-fatal): %v", tmp, err)
|
||
}
|
||
won, err := f.rediscache.RenameNX(opCtx, tmp, dest)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, nil
|
||
}
|
||
if !won {
|
||
_ = f.rediscache.Del(opCtx, tmp) // 别人先建好了,用他的
|
||
} else if err := f.rediscache.Expire(opCtx, dest, hotSnapshotTTL); err != nil {
|
||
// RENAMENX 把 tmp 的 1 分钟 TTL 一起带给了 dest。若这里没改成
|
||
// 快照寿命,dest 会在一分钟后消失:第 2 页因此重建快照、
|
||
// snapshot_rebuilt=true、客户端重置到第 1 页——而重建的快照又只
|
||
// 活 1 分钟,于是永远翻不到第 2 页。宁可删掉让下一次请求干净重建。
|
||
log.Printf("feed: expire hot snapshot %s failed, dropping it: %v", dest, err)
|
||
_ = f.rediscache.Del(opCtx, dest)
|
||
}
|
||
}
|
||
|
||
// 只要分数 > 0 的成员:加一次再减一次会把 member 留在桶里、分数归 0,
|
||
// 这类视频此刻没有任何互动,不应出现在榜上。DB 路径天然只返回"窗口内
|
||
// 有行"的视频,两者因此一致。
|
||
members, err := f.rediscache.ZRevRangeByScore(opCtx, dest, "+inf", "(0", int64(offset), int64(limit))
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, nil
|
||
}
|
||
if len(members) == 0 {
|
||
if offset > 0 {
|
||
return ListByPopularityResponse{
|
||
VideoList: []FeedVideoItem{},
|
||
AsOf: asOf.Unix(),
|
||
NextOffset: offset,
|
||
HasMore: false,
|
||
RankingSource: "hot",
|
||
SnapshotRebuilt: !exists,
|
||
}, true, nil
|
||
}
|
||
// 空榜:可能是真的空,也可能是丢桶。都交给 DB 窗口判一次。
|
||
return ListByPopularityResponse{}, false, nil
|
||
}
|
||
|
||
ids := parseHotMembers(members)
|
||
videos, err := f.repo.GetByIDs(ctx, ids)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, err
|
||
}
|
||
byID := make(map[uint]*video.Video, len(videos))
|
||
for _, v := range videos {
|
||
byID[v.ID] = v
|
||
}
|
||
ordered := make([]*video.Video, 0, len(ids))
|
||
for _, id := range ids {
|
||
if v := byID[id]; v != nil {
|
||
ordered = append(ordered, v)
|
||
}
|
||
}
|
||
items, err := f.buildFeedVideos(ctx, ordered, viewer)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, false, err
|
||
}
|
||
return ListByPopularityResponse{
|
||
VideoList: items,
|
||
AsOf: asOf.Unix(),
|
||
// 按 ZSET 返回的 member 数推进:视频被删后 member 仍在,
|
||
// 按存活视频数推进会重复读到已经跳过的位置。
|
||
NextOffset: offset + len(members),
|
||
HasMore: len(members) == limit,
|
||
RankingSource: "hot",
|
||
SnapshotRebuilt: !exists && offset > 0,
|
||
}, true, nil
|
||
}
|
||
|
||
func parseHotMembers(members []string) []uint {
|
||
ids := make([]uint, 0, len(members))
|
||
for _, m := range members {
|
||
u, err := strconv.ParseUint(m, 10, 64) // 兼容补零与旧格式
|
||
if err == nil && u > 0 {
|
||
ids = append(ids, uint(u))
|
||
}
|
||
}
|
||
return ids
|
||
}
|
||
|
||
func (f *FeedService) listByHotWindowDB(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, error) {
|
||
from, to := hotWindowBounds(asOf)
|
||
rows, err := f.repo.ListHotWindow(ctx, from, to, limit, offset)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
|
||
if len(rows) == 0 && offset > 0 {
|
||
return ListByPopularityResponse{
|
||
VideoList: []FeedVideoItem{},
|
||
AsOf: asOf.Unix(),
|
||
NextOffset: offset,
|
||
HasMore: false,
|
||
RankingSource: "hot_db",
|
||
}, nil
|
||
}
|
||
if len(rows) == 0 {
|
||
// 窗口内没有任何互动:给"最新",而不是给一个空页面。
|
||
latest, err := f.repo.ListLatest(ctx, limit, time.Time{})
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
items, err := f.buildFeedVideos(ctx, latest, viewer)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
return ListByPopularityResponse{
|
||
VideoList: items, AsOf: asOf.Unix(),
|
||
// 这一支是"兜底给点东西看",不是可分页的列表:ListLatest 不收 offset,
|
||
// 若这里回一个 next_offset,第 2 页会落到 ListHotWindow 的空结果上并返回空页。
|
||
NextOffset: 0, HasMore: false, RankingSource: "latest",
|
||
}, nil
|
||
}
|
||
|
||
ids := make([]uint, 0, len(rows))
|
||
for _, r := range rows {
|
||
ids = append(ids, r.VideoID)
|
||
}
|
||
videos, err := f.repo.GetByIDs(ctx, ids)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
byID := make(map[uint]*video.Video, len(videos))
|
||
for _, v := range videos {
|
||
byID[v.ID] = v
|
||
}
|
||
ordered := make([]*video.Video, 0, len(ids))
|
||
for _, id := range ids {
|
||
if v := byID[id]; v != nil {
|
||
ordered = append(ordered, v)
|
||
}
|
||
}
|
||
items, err := f.buildFeedVideos(ctx, ordered, viewer)
|
||
if err != nil {
|
||
return ListByPopularityResponse{}, err
|
||
}
|
||
return ListByPopularityResponse{
|
||
VideoList: items, AsOf: asOf.Unix(),
|
||
NextOffset: offset + len(rows),
|
||
HasMore: len(rows) == limit,
|
||
RankingSource: "hot_db",
|
||
}, nil
|
||
}
|
||
|
||
// 将 Video 列表转换为 FeedVideoItem 列表,并批量查询填充当前用户对所有视频的点赞状态
|
||
func (f *FeedService) buildFeedVideos(ctx context.Context, videos []*video.Video, viewerAccountID uint) ([]FeedVideoItem, error) {
|
||
feedVideos := make([]FeedVideoItem, 0, len(videos))
|
||
videoIDs := make([]uint, len(videos))
|
||
for i, v := range videos {
|
||
videoIDs[i] = v.ID
|
||
}
|
||
likedMap, err := f.likeRepo.BatchGetLiked(ctx, videoIDs, viewerAccountID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
for _, video := range videos {
|
||
feedVideos = append(feedVideos, FeedVideoItem{
|
||
ID: video.ID,
|
||
Author: FeedAuthor{ID: video.AuthorID, Username: video.Username},
|
||
Title: video.Title,
|
||
Description: video.Description,
|
||
PlayURL: video.PlayURL,
|
||
CoverURL: video.CoverURL,
|
||
CreateTime: video.CreateTime.Unix(),
|
||
LikesCount: video.LikesCount,
|
||
IsLiked: likedMap[video.ID],
|
||
})
|
||
}
|
||
return feedVideos, nil
|
||
}
|
||
|
||
// 将视频列表按照给定的 ID 顺序(orderedIDs)重新排序
|
||
func buildOrderedResult(orderedIDs []uint, dataMap map[uint]*video.Video) []*video.Video {
|
||
res := make([]*video.Video, 0, len(orderedIDs))
|
||
for _, id := range orderedIDs {
|
||
if v, exits := dataMap[id]; exits && v != nil {
|
||
res = append(res, v)
|
||
}
|
||
}
|
||
return res
|
||
}
|
||
|
||
func (f *FeedService) ListByTag(ctx context.Context, tagName string, limit int, viewerAccountID uint) ([]FeedVideoItem, error) {
|
||
videos, err := f.repo.ListByTag(ctx, tagName, limit)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||
}
|