Commit ·
cea9127
1
Parent(s): 6f5981f
feat: view_count Redis incr, history upsert, pytest config
Browse files- vod.py service: increment_view_count now writes to Redis incr (no DB lock)
flush_view_counts() batch-writes deltas back to DB every 5 minutes
- scheduler: add flush_view_counts job (IntervalTrigger 5min)
- router/vod: update increment_view_count call (no db param)
- router/history: upsert logic already existed, add response body {id, progress}
change error/unknown messages to ASCII to avoid Windows GBK issues
- pytest.ini: set asyncio_mode=auto and asyncio_default_fixture_loop_scope=function
eliminates all PytestDeprecationWarning
- app/routers/user/history.py +9 -3
- app/routers/user/vod.py +2 -2
- app/services/scheduler.py +17 -9
- app/services/vod.py +76 -4
- pytest.ini +3 -0
app/routers/user/history.py
CHANGED
|
@@ -48,7 +48,7 @@ async def list_history(
|
|
| 48 |
HistoryItem(
|
| 49 |
id=h.id,
|
| 50 |
vod_id=h.vod_id,
|
| 51 |
-
vod_name=vod[1] if vod else "
|
| 52 |
vod_cover=vod[2] if vod else None,
|
| 53 |
source_id=h.source_id,
|
| 54 |
episode=h.episode,
|
|
@@ -70,6 +70,11 @@ async def record_history(
|
|
| 70 |
user: User = Depends(get_current_user),
|
| 71 |
db: AsyncSession = Depends(get_db),
|
| 72 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
existing = await db.execute(
|
| 74 |
select(PlayHistory).where(
|
| 75 |
PlayHistory.user_id == user.id,
|
|
@@ -84,6 +89,7 @@ async def record_history(
|
|
| 84 |
history.play_url = req.play_url
|
| 85 |
history.progress = req.progress
|
| 86 |
history.duration = req.duration
|
|
|
|
| 87 |
else:
|
| 88 |
history = PlayHistory(
|
| 89 |
user_id=user.id,
|
|
@@ -97,7 +103,7 @@ async def record_history(
|
|
| 97 |
db.add(history)
|
| 98 |
|
| 99 |
await db.flush()
|
| 100 |
-
return ApiResponse.ok()
|
| 101 |
|
| 102 |
|
| 103 |
@router.delete("/{history_id}", response_model=ApiResponse)
|
|
@@ -112,6 +118,6 @@ async def delete_history(
|
|
| 112 |
)
|
| 113 |
)
|
| 114 |
if result.rowcount == 0:
|
| 115 |
-
return ApiResponse.fail(40401, "
|
| 116 |
|
| 117 |
return ApiResponse.ok()
|
|
|
|
| 48 |
HistoryItem(
|
| 49 |
id=h.id,
|
| 50 |
vod_id=h.vod_id,
|
| 51 |
+
vod_name=vod[1] if vod else "unknown",
|
| 52 |
vod_cover=vod[2] if vod else None,
|
| 53 |
source_id=h.source_id,
|
| 54 |
episode=h.episode,
|
|
|
|
| 70 |
user: User = Depends(get_current_user),
|
| 71 |
db: AsyncSession = Depends(get_db),
|
| 72 |
):
|
| 73 |
+
"""
|
| 74 |
+
Upsert play history.
|
| 75 |
+
Match key: user_id + vod_id + source_id.
|
| 76 |
+
Update episode/play_url/progress/duration if exists, insert if not.
|
| 77 |
+
"""
|
| 78 |
existing = await db.execute(
|
| 79 |
select(PlayHistory).where(
|
| 80 |
PlayHistory.user_id == user.id,
|
|
|
|
| 89 |
history.play_url = req.play_url
|
| 90 |
history.progress = req.progress
|
| 91 |
history.duration = req.duration
|
| 92 |
+
# updated_at is handled by ORM onupdate
|
| 93 |
else:
|
| 94 |
history = PlayHistory(
|
| 95 |
user_id=user.id,
|
|
|
|
| 103 |
db.add(history)
|
| 104 |
|
| 105 |
await db.flush()
|
| 106 |
+
return ApiResponse.ok({"id": history.id, "progress": history.progress})
|
| 107 |
|
| 108 |
|
| 109 |
@router.delete("/{history_id}", response_model=ApiResponse)
|
|
|
|
| 118 |
)
|
| 119 |
)
|
| 120 |
if result.rowcount == 0:
|
| 121 |
+
return ApiResponse.fail(40401, "record not found")
|
| 122 |
|
| 123 |
return ApiResponse.ok()
|
app/routers/user/vod.py
CHANGED
|
@@ -224,7 +224,7 @@ async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
|
|
| 224 |
cached = await cache_get(cache_key)
|
| 225 |
if cached is not None:
|
| 226 |
# 即使命中缓存仍递增播放次数
|
| 227 |
-
await increment_view_count(
|
| 228 |
return ApiResponse.ok(cached)
|
| 229 |
|
| 230 |
result = await db.execute(select(Vod).where(Vod.id == vod_id, Vod.is_hidden == False))
|
|
@@ -232,7 +232,7 @@ async def get_vod(vod_id: int, db: AsyncSession = Depends(get_db)):
|
|
| 232 |
if not vod:
|
| 233 |
return ApiResponse.fail(40401, "影片不存在")
|
| 234 |
|
| 235 |
-
await increment_view_count(
|
| 236 |
|
| 237 |
cat_result = await db.execute(select(Category.name).where(Category.id == vod.category_id))
|
| 238 |
cat_name = cat_result.scalar_one_or_none()
|
|
|
|
| 224 |
cached = await cache_get(cache_key)
|
| 225 |
if cached is not None:
|
| 226 |
# 即使命中缓存仍递增播放次数
|
| 227 |
+
await increment_view_count(vod_id)
|
| 228 |
return ApiResponse.ok(cached)
|
| 229 |
|
| 230 |
result = await db.execute(select(Vod).where(Vod.id == vod_id, Vod.is_hidden == False))
|
|
|
|
| 232 |
if not vod:
|
| 233 |
return ApiResponse.fail(40401, "影片不存在")
|
| 234 |
|
| 235 |
+
await increment_view_count(vod_id)
|
| 236 |
|
| 237 |
cat_result = await db.execute(select(Category.name).where(Category.id == vod.category_id))
|
| 238 |
cat_name = cat_result.scalar_one_or_none()
|
app/services/scheduler.py
CHANGED
|
@@ -15,8 +15,7 @@ scheduler = AsyncIOScheduler()
|
|
| 15 |
def start_scheduler():
|
| 16 |
sync_hour = settings.SYNC_CRON_HOUR
|
| 17 |
|
| 18 |
-
|
| 19 |
-
for job_id in ("sync_daily", "sync_weekly", "sync_monthly", "health_check"):
|
| 20 |
if scheduler.get_job(job_id):
|
| 21 |
scheduler.remove_job(job_id)
|
| 22 |
|
|
@@ -24,7 +23,7 @@ def start_scheduler():
|
|
| 24 |
collector.sync_all,
|
| 25 |
trigger=CronTrigger(hour=sync_hour, minute=0),
|
| 26 |
id="sync_daily",
|
| 27 |
-
name="
|
| 28 |
kwargs={"range_type": "daily"},
|
| 29 |
misfire_grace_time=3600,
|
| 30 |
)
|
|
@@ -33,7 +32,7 @@ def start_scheduler():
|
|
| 33 |
collector.sync_all,
|
| 34 |
trigger=CronTrigger(day_of_week="mon", hour=sync_hour, minute=30),
|
| 35 |
id="sync_weekly",
|
| 36 |
-
name="
|
| 37 |
kwargs={"range_type": "weekly"},
|
| 38 |
misfire_grace_time=7200,
|
| 39 |
)
|
|
@@ -42,26 +41,35 @@ def start_scheduler():
|
|
| 42 |
collector.sync_all,
|
| 43 |
trigger=CronTrigger(day=1, hour=sync_hour, minute=45),
|
| 44 |
id="sync_monthly",
|
| 45 |
-
name="
|
| 46 |
kwargs={"range_type": "monthly"},
|
| 47 |
misfire_grace_time=14400,
|
| 48 |
)
|
| 49 |
|
| 50 |
-
# 源站健康检查:每 30 分钟执行一次
|
| 51 |
from app.services.health import run_health_checks
|
| 52 |
scheduler.add_job(
|
| 53 |
run_health_checks,
|
| 54 |
trigger=IntervalTrigger(minutes=30),
|
| 55 |
id="health_check",
|
| 56 |
-
name="
|
| 57 |
misfire_grace_time=300,
|
| 58 |
)
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
scheduler.start()
|
| 61 |
-
logger.info(f"Scheduler started
|
| 62 |
|
| 63 |
|
| 64 |
def stop_scheduler():
|
| 65 |
if scheduler.running:
|
| 66 |
scheduler.shutdown(wait=False)
|
| 67 |
-
logger.info("Scheduler stopped")
|
|
|
|
| 15 |
def start_scheduler():
|
| 16 |
sync_hour = settings.SYNC_CRON_HOUR
|
| 17 |
|
| 18 |
+
for job_id in ("sync_daily", "sync_weekly", "sync_monthly", "health_check", "flush_view_counts"):
|
|
|
|
| 19 |
if scheduler.get_job(job_id):
|
| 20 |
scheduler.remove_job(job_id)
|
| 21 |
|
|
|
|
| 23 |
collector.sync_all,
|
| 24 |
trigger=CronTrigger(hour=sync_hour, minute=0),
|
| 25 |
id="sync_daily",
|
| 26 |
+
name="daily sync",
|
| 27 |
kwargs={"range_type": "daily"},
|
| 28 |
misfire_grace_time=3600,
|
| 29 |
)
|
|
|
|
| 32 |
collector.sync_all,
|
| 33 |
trigger=CronTrigger(day_of_week="mon", hour=sync_hour, minute=30),
|
| 34 |
id="sync_weekly",
|
| 35 |
+
name="weekly sync",
|
| 36 |
kwargs={"range_type": "weekly"},
|
| 37 |
misfire_grace_time=7200,
|
| 38 |
)
|
|
|
|
| 41 |
collector.sync_all,
|
| 42 |
trigger=CronTrigger(day=1, hour=sync_hour, minute=45),
|
| 43 |
id="sync_monthly",
|
| 44 |
+
name="monthly sync",
|
| 45 |
kwargs={"range_type": "monthly"},
|
| 46 |
misfire_grace_time=14400,
|
| 47 |
)
|
| 48 |
|
|
|
|
| 49 |
from app.services.health import run_health_checks
|
| 50 |
scheduler.add_job(
|
| 51 |
run_health_checks,
|
| 52 |
trigger=IntervalTrigger(minutes=30),
|
| 53 |
id="health_check",
|
| 54 |
+
name="source health check",
|
| 55 |
misfire_grace_time=300,
|
| 56 |
)
|
| 57 |
|
| 58 |
+
# view_count Redis incr -> DB flush, every 5 minutes
|
| 59 |
+
from app.services.vod import flush_view_counts
|
| 60 |
+
scheduler.add_job(
|
| 61 |
+
flush_view_counts,
|
| 62 |
+
trigger=IntervalTrigger(minutes=5),
|
| 63 |
+
id="flush_view_counts",
|
| 64 |
+
name="flush view counts",
|
| 65 |
+
misfire_grace_time=60,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
scheduler.start()
|
| 69 |
+
logger.info(f"Scheduler started, sync_hour={sync_hour}")
|
| 70 |
|
| 71 |
|
| 72 |
def stop_scheduler():
|
| 73 |
if scheduler.running:
|
| 74 |
scheduler.shutdown(wait=False)
|
| 75 |
+
logger.info("Scheduler stopped")
|
app/services/vod.py
CHANGED
|
@@ -34,7 +34,79 @@ async def batch_get_source_counts(db: AsyncSession, vod_ids: list[int]) -> dict[
|
|
| 34 |
return {row[0]: row[1] for row in result.all()}
|
| 35 |
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
return {row[0]: row[1] for row in result.all()}
|
| 35 |
|
| 36 |
|
| 37 |
+
# Redis key: binv:view_count:{vod_id} 存储待回写的增量
|
| 38 |
+
_VIEW_COUNT_PREFIX = "binv:vc:"
|
| 39 |
+
_VIEW_COUNT_PENDING = "binv:vc:pending" # Set,记录有待回写的 vod_id
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def increment_view_count(vod_id: int) -> None:
|
| 43 |
+
"""
|
| 44 |
+
播放次数 +1,写入 Redis。
|
| 45 |
+
不再直接 UPDATE 数据库,避免高并发下行锁竞争。
|
| 46 |
+
由定时任务 flush_view_counts 批量回写。
|
| 47 |
+
Redis 不可用时降级为无操作(计数丢失但不影响功能)。
|
| 48 |
+
"""
|
| 49 |
+
from app.cache import get_redis
|
| 50 |
+
r = await get_redis()
|
| 51 |
+
if r is None:
|
| 52 |
+
return
|
| 53 |
+
try:
|
| 54 |
+
key = f"{_VIEW_COUNT_PREFIX}{vod_id}"
|
| 55 |
+
await r.incr(key)
|
| 56 |
+
await r.sadd(_VIEW_COUNT_PENDING, str(vod_id))
|
| 57 |
+
except Exception:
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
async def flush_view_counts() -> int:
|
| 62 |
+
"""
|
| 63 |
+
将 Redis 中累计的 view_count 增量批量回写到数据库。
|
| 64 |
+
由定时任务每 5 分钟调用一次。
|
| 65 |
+
返回回写的影片数量。
|
| 66 |
+
"""
|
| 67 |
+
from app.cache import get_redis
|
| 68 |
+
from app.database import async_session
|
| 69 |
+
|
| 70 |
+
r = await get_redis()
|
| 71 |
+
if r is None:
|
| 72 |
+
return 0
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
# 取出所有待回写的 vod_id(原子操作:SMEMBERS + DEL pending set)
|
| 76 |
+
vod_ids_raw = await r.smembers(_VIEW_COUNT_PENDING)
|
| 77 |
+
if not vod_ids_raw:
|
| 78 |
+
return 0
|
| 79 |
+
|
| 80 |
+
# 删除 pending set(已取出,后续新的 incr 会重新加入)
|
| 81 |
+
await r.delete(_VIEW_COUNT_PENDING)
|
| 82 |
+
|
| 83 |
+
vod_ids = [int(v) for v in vod_ids_raw]
|
| 84 |
+
|
| 85 |
+
# 逐个取出增量并删除 key
|
| 86 |
+
updates: dict[int, int] = {}
|
| 87 |
+
for vod_id in vod_ids:
|
| 88 |
+
key = f"{_VIEW_COUNT_PREFIX}{vod_id}"
|
| 89 |
+
delta_raw = await r.getdel(key)
|
| 90 |
+
if delta_raw and int(delta_raw) > 0:
|
| 91 |
+
updates[vod_id] = int(delta_raw)
|
| 92 |
+
|
| 93 |
+
if not updates:
|
| 94 |
+
return 0
|
| 95 |
+
|
| 96 |
+
# 批量 UPDATE
|
| 97 |
+
async with async_session() as db:
|
| 98 |
+
for vod_id, delta in updates.items():
|
| 99 |
+
await db.execute(
|
| 100 |
+
Vod.__table__.update()
|
| 101 |
+
.where(Vod.id == vod_id)
|
| 102 |
+
.values(view_count=Vod.view_count + delta)
|
| 103 |
+
)
|
| 104 |
+
await db.commit()
|
| 105 |
+
|
| 106 |
+
return len(updates)
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
import logging
|
| 110 |
+
logging.getLogger("vod").warning(f"flush_view_counts error: {e}")
|
| 111 |
+
return 0
|
| 112 |
+
|
pytest.ini
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
asyncio_mode = auto
|
| 3 |
+
asyncio_default_fixture_loop_scope = function
|