File size: 3,560 Bytes
bf34e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea9127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.category import Category
from app.models.vod import Vod
from app.models.vod_source import VodSource


async def get_vod_by_id(db: AsyncSession, vod_id: int, hidden_ok: bool = False) -> Vod | None:
    query = select(Vod).where(Vod.id == vod_id)
    if not hidden_ok:
        query = query.where(Vod.is_hidden == False)
    result = await db.execute(query)
    return result.scalar_one_or_none()


async def batch_get_category_names(db: AsyncSession, category_ids: list[int]) -> dict[int, str]:
    if not category_ids:
        return {}
    result = await db.execute(
        select(Category.id, Category.name).where(Category.id.in_(category_ids))
    )
    return {row[0]: row[1] for row in result.all()}


async def batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[int, int]:
    if not vod_ids:
        return {}
    result = await db.execute(
        select(VodSource.vod_id, func.count(VodSource.id))
        .where(VodSource.vod_id.in_(vod_ids), VodSource.is_available == True)
        .group_by(VodSource.vod_id)
    )
    return {row[0]: row[1] for row in result.all()}


# Redis key: binv:view_count:{vod_id}  存储待回写的增量
_VIEW_COUNT_PREFIX = "binv:vc:"
_VIEW_COUNT_PENDING = "binv:vc:pending"   # Set,记录有待回写的 vod_id


async def increment_view_count(vod_id: int) -> None:
    """
    播放次数 +1,写入 Redis。
    不再直接 UPDATE 数据库,避免高并发下行锁竞争。
    由定时任务 flush_view_counts 批量回写。
    Redis 不可用时降级为无操作(计数丢失但不影响功能)。
    """
    from app.cache import get_redis
    r = await get_redis()
    if r is None:
        return
    try:
        key = f"{_VIEW_COUNT_PREFIX}{vod_id}"
        await r.incr(key)
        await r.sadd(_VIEW_COUNT_PENDING, str(vod_id))
    except Exception:
        pass


async def flush_view_counts() -> int:
    """
    将 Redis 中累计的 view_count 增量批量回写到数据库。
    由定时任务每 5 分钟调用一次。
    返回回写的影片数量。
    """
    from app.cache import get_redis
    from app.database import async_session

    r = await get_redis()
    if r is None:
        return 0

    try:
        # 取出所有待回写的 vod_id(原子操作:SMEMBERS + DEL pending set)
        vod_ids_raw = await r.smembers(_VIEW_COUNT_PENDING)
        if not vod_ids_raw:
            return 0

        # 删除 pending set(已取出,后续新的 incr 会重新加入)
        await r.delete(_VIEW_COUNT_PENDING)

        vod_ids = [int(v) for v in vod_ids_raw]

        # 逐个取出增量并删除 key
        updates: dict[int, int] = {}
        for vod_id in vod_ids:
            key = f"{_VIEW_COUNT_PREFIX}{vod_id}"
            delta_raw = await r.getdel(key)
            if delta_raw and int(delta_raw) > 0:
                updates[vod_id] = int(delta_raw)

        if not updates:
            return 0

        # 批量 UPDATE
        async with async_session() as db:
            for vod_id, delta in updates.items():
                await db.execute(
                    Vod.__table__.update()
                    .where(Vod.id == vod_id)
                    .values(view_count=Vod.view_count + delta)
                )
            await db.commit()

        return len(updates)

    except Exception as e:
        import logging
        logging.getLogger("vod").warning(f"flush_view_counts error: {e}")
        return 0