「抓不到最新的」有两个叠加的原因: 1. 采集卡死时 `_run_due_task` 是内联 await,execute_task 里的 wait_for 又在等 一个不响应取消的协程 —— 整个调度循环(连同自动追加、每日推送、其他任务) 一起停 65 分钟。现在采集丢到后台任务里跑,循环照常 tick,reap_stale_runs 也能按时回收。实测任务 25 最近 8 次运行有 4 次这样。 2. 超级编导自动追加在 10-25 因密码错误被停到 11-24(防锁号),新作品进不来。 已把 25 号的调度钟拨回现在,补进了 10-31 那条。 标签矩阵:博主名字左边在粉丝数之后加「主页总获赞」和「第一条视频发布日期」 (查全库最早的作品时间,不受 7/14/30 天窗口限制)。
454 lines
17 KiB
Python
454 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Copyright (c) 2025 [email protected]
|
|
#
|
|
# This file is part of MediaCrawler project.
|
|
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tests/test_monitor_scheduler.py
|
|
# GitHub: https://github.com/NanmiCoder
|
|
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
|
|
#
|
|
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
|
# 1. 不得用于任何商业用途。
|
|
# 2. 使用时应遵守目标平台的使用条款和robots.txt规则。
|
|
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
|
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
|
# 5. 不得用于任何非法或不当的用途。
|
|
#
|
|
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
|
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
|
|
|
"""Tests for the monitor scheduler's firing, deferral and recovery rules."""
|
|
|
|
import asyncio
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy import select
|
|
|
|
from api.monitor import db as monitor_db
|
|
from api.monitor import scheduler as scheduler_module
|
|
from api.monitor.models import (
|
|
MODE_CREATOR,
|
|
MonitorRun,
|
|
MonitorTarget,
|
|
MonitorTask,
|
|
RUN_INTERRUPTED,
|
|
RUN_PENDING,
|
|
RUN_RUNNING,
|
|
RUN_SUCCESS,
|
|
)
|
|
from api.monitor.scheduler import MonitorScheduler
|
|
from api.monitor.settings import set_cookie, set_setting
|
|
from tools.time_util import get_current_timestamp
|
|
|
|
MS_PER_MINUTE = 60_000
|
|
|
|
|
|
class FakeCrawlerManager:
|
|
"""Stands in for the global subprocess singleton."""
|
|
|
|
def __init__(self, busy: bool = False) -> None:
|
|
self.busy = busy
|
|
|
|
def is_busy(self) -> bool:
|
|
return self.busy
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def db(tmp_path):
|
|
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
|
|
await monitor_db.init_db()
|
|
async with monitor_db.get_session() as session:
|
|
await set_cookie(session, "web_session=test")
|
|
yield monitor_db
|
|
await monitor_db.dispose_engine()
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def executed(monkeypatch):
|
|
"""Record execute_task calls instead of launching a real crawl."""
|
|
calls: list[tuple[int, str]] = []
|
|
|
|
async def _fake_execute(task_id: int, trigger: str = "manual"):
|
|
calls.append((task_id, trigger))
|
|
|
|
monkeypatch.setattr(scheduler_module, "execute_task", _fake_execute)
|
|
return calls
|
|
|
|
|
|
async def _tick(scheduler: MonitorScheduler) -> None:
|
|
"""tick + 等后台采集结束。
|
|
|
|
采集现在跑在后台任务里(卡死的一轮不能堵住整个调度循环),断言调用记录之前
|
|
得先把它等回来。
|
|
"""
|
|
await scheduler.tick()
|
|
await scheduler.drain()
|
|
|
|
|
|
async def _make_task(
|
|
next_run_at, enabled: bool = True, interval: int = 60, platform: str = "xhs"
|
|
) -> int:
|
|
async with monitor_db.get_session() as session:
|
|
now = get_current_timestamp()
|
|
task = MonitorTask(
|
|
name="t",
|
|
platform=platform,
|
|
mode=MODE_CREATOR,
|
|
enabled=enabled,
|
|
interval_minutes=interval,
|
|
max_notes_count=20,
|
|
enable_comments=True,
|
|
max_comments_count=50,
|
|
run_timeout_seconds=3600,
|
|
next_run_at=next_run_at,
|
|
last_status="idle",
|
|
created_at=now,
|
|
updated_at=now,
|
|
)
|
|
session.add(task)
|
|
await session.flush()
|
|
session.add(
|
|
MonitorTarget(
|
|
task_id=task.id,
|
|
kind=MODE_CREATOR,
|
|
external_id="abc123",
|
|
xsec_token="",
|
|
xsec_source="",
|
|
raw_value="abc123",
|
|
label="abc123",
|
|
enabled=True,
|
|
created_at=now,
|
|
)
|
|
)
|
|
return task.id
|
|
|
|
|
|
async def _get_task(task_id: int) -> MonitorTask:
|
|
async with monitor_db.get_session() as session:
|
|
return await session.get(MonitorTask, task_id)
|
|
|
|
|
|
class TestFiring:
|
|
@pytest.mark.asyncio
|
|
async def test_due_task_runs_and_advances(self, monkeypatch, db, executed):
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
past = get_current_timestamp() - MS_PER_MINUTE
|
|
task_id = await _make_task(past)
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == [(task_id, "scheduled")]
|
|
task = await _get_task(task_id)
|
|
# Fixed-delay: the next fire is measured from now, not from the missed slot.
|
|
assert task.next_run_at > get_current_timestamp()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_future_task_does_not_run(self, monkeypatch, db, executed):
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
await _make_task(get_current_timestamp() + 10 * MS_PER_MINUTE)
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_disabled_task_does_not_run(self, monkeypatch, db, executed):
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
await _make_task(get_current_timestamp() - MS_PER_MINUTE, enabled=False)
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_the_cookie_gate_reads_the_tasks_own_platform(
|
|
self, monkeypatch, db, executed
|
|
):
|
|
"""cookie 闸门要按任务自己的平台取。
|
|
|
|
以前这里是 ``get_cookie(session)``(默认小红书)—— 只有小红书时看不出问题,
|
|
接上抖音后,抖音任务会因为读的是小红书那份 cookie 而永远不被触发,且不报错。
|
|
"""
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
async with monitor_db.get_session() as session:
|
|
await set_cookie(session, "sessionid=dy-secret", "dy")
|
|
|
|
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == [(task_id, "scheduled")]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cdp_mode_frees_a_task_from_the_cookie_gate(
|
|
self, monkeypatch, db, executed
|
|
):
|
|
"""开着 CDP 时不该再要求先粘 cookie。
|
|
|
|
CDP 模式下登录态来自被接管的那台浏览器,粘不粘 cookie 都由不得它 —— 不放行的话,
|
|
选了「接管已有 Chrome」却没粘 cookie 的用户会发现任务永远不跑,而且什么错都不报。
|
|
"""
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
async with monitor_db.get_session() as session:
|
|
await set_setting(session, "system.cdp_enabled", "true")
|
|
|
|
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == [(task_id, "scheduled")]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_long_outage_coalesces_into_one_run(self, monkeypatch, db, executed):
|
|
"""A missed schedule fires once, not once per missed interval."""
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
# Due two days ago on a 1-hour interval.
|
|
await _make_task(get_current_timestamp() - 48 * 60 * MS_PER_MINUTE)
|
|
|
|
scheduler = MonitorScheduler()
|
|
await scheduler.tick()
|
|
await scheduler.drain()
|
|
await scheduler.tick()
|
|
await scheduler.drain()
|
|
|
|
assert len(executed) == 1
|
|
|
|
|
|
class TestNonBlocking:
|
|
@pytest.mark.asyncio
|
|
async def test_a_hanging_run_does_not_block_the_scheduler(self, monkeypatch, db):
|
|
"""卡死的一轮不能钉住整个循环 —— 其他任务和自动追加都靠这个 tick。
|
|
|
|
实测:抖音采集协程偶尔不响应取消,内联 await 会让循环停 65 分钟。
|
|
"""
|
|
|
|
async def never(task_id, trigger="scheduled"):
|
|
await asyncio.Event().wait()
|
|
|
|
monkeypatch.setattr(scheduler_module, "execute_task", never)
|
|
await _make_task(get_current_timestamp() - MS_PER_MINUTE)
|
|
scheduler = MonitorScheduler()
|
|
|
|
# 必须在很短时间内返回,而不是等采集结束。
|
|
await asyncio.wait_for(scheduler.tick(), timeout=2)
|
|
|
|
assert len(scheduler._running_tasks) == 1
|
|
for task in list(scheduler._running_tasks.values()):
|
|
task.cancel()
|
|
|
|
|
|
class TestDeferral:
|
|
@pytest.mark.asyncio
|
|
async def test_busy_crawler_defers_without_advancing(self, monkeypatch, db, executed):
|
|
"""A manual crawl must not consume the monitor task's slot or lose it."""
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=True))
|
|
due_at = get_current_timestamp() - MS_PER_MINUTE
|
|
task_id = await _make_task(due_at)
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == []
|
|
task = await _get_task(task_id)
|
|
# Still due, so the next free tick picks it up rather than skipping a cycle.
|
|
assert task.next_run_at == due_at
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_deferred_task_runs_once_crawler_frees_up(self, monkeypatch, db, executed):
|
|
fake = FakeCrawlerManager(busy=True)
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", fake)
|
|
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE)
|
|
|
|
scheduler = MonitorScheduler()
|
|
await scheduler.tick()
|
|
await scheduler.drain()
|
|
assert executed == []
|
|
|
|
fake.busy = False
|
|
await scheduler.tick()
|
|
await scheduler.drain()
|
|
assert executed == [(task_id, "scheduled")]
|
|
|
|
|
|
class TestCookieGuard:
|
|
@pytest.mark.asyncio
|
|
async def test_no_cookie_blocks_run_and_keeps_task_due(self, monkeypatch, db, executed):
|
|
"""Without a cookie every run would be an auth failure; skip instead."""
|
|
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
|
async with monitor_db.get_session() as session:
|
|
from api.monitor.settings import cookie_key, delete_setting
|
|
|
|
await delete_setting(session, cookie_key("xhs"))
|
|
|
|
due_at = get_current_timestamp() - MS_PER_MINUTE
|
|
task_id = await _make_task(due_at)
|
|
|
|
await _tick(MonitorScheduler())
|
|
|
|
assert executed == []
|
|
task = await _get_task(task_id)
|
|
# Left due so it starts working the moment a cookie is pasted.
|
|
assert task.next_run_at == due_at
|
|
|
|
|
|
class TestRecovery:
|
|
@pytest.mark.asyncio
|
|
async def test_running_runs_are_marked_interrupted(self, db):
|
|
"""A run left 'running' cannot be alive -- its process died with the server."""
|
|
async with monitor_db.get_session() as session:
|
|
now = get_current_timestamp()
|
|
task = MonitorTask(
|
|
name="t", platform="xhs", mode=MODE_CREATOR, enabled=True,
|
|
interval_minutes=60, max_notes_count=20, enable_comments=True,
|
|
max_comments_count=50, run_timeout_seconds=3600,
|
|
next_run_at=now, last_status="running", created_at=now, updated_at=now,
|
|
)
|
|
session.add(task)
|
|
await session.flush()
|
|
session.add(
|
|
MonitorRun(
|
|
task_id=task.id, trigger="scheduled", status=RUN_RUNNING,
|
|
phase=MODE_CREATOR, save_data_path="", queued_at=now, not_before=0,
|
|
started_at=now, max_comments_count=50,
|
|
)
|
|
)
|
|
|
|
await MonitorScheduler().recover()
|
|
|
|
async with monitor_db.get_session() as session:
|
|
run = await session.scalar(select(MonitorRun))
|
|
assert run.status == RUN_INTERRUPTED
|
|
assert run.finished_at is not None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pending_runs_are_also_cleaned_up(self, db):
|
|
"""挂在 ``pending`` 的 run 同样是残留,必须一起收。
|
|
|
|
那一行是上一轮建的,可它后面的采集根本没机会开始(进程被重启,或采集那条路抛了
|
|
异常)。只清 ``running`` 的话,它会永远挂在界面上显示「排队中」——
|
|
用户看到的就是任务卡死了。
|
|
"""
|
|
async with monitor_db.get_session() as session:
|
|
now = get_current_timestamp()
|
|
task = MonitorTask(
|
|
name="t", platform="dy", mode=MODE_CREATOR, enabled=True,
|
|
interval_minutes=60, max_notes_count=20, enable_comments=False,
|
|
max_comments_count=50, run_timeout_seconds=3600,
|
|
next_run_at=now, last_status="pending", created_at=now, updated_at=now,
|
|
)
|
|
session.add(task)
|
|
await session.flush()
|
|
session.add(
|
|
MonitorRun(
|
|
task_id=task.id, trigger="manual", status=RUN_PENDING,
|
|
phase=MODE_CREATOR, save_data_path="", queued_at=now, not_before=0,
|
|
max_comments_count=50,
|
|
)
|
|
)
|
|
|
|
await MonitorScheduler().recover()
|
|
|
|
async with monitor_db.get_session() as session:
|
|
run = await session.scalar(select(MonitorRun))
|
|
assert run.status == RUN_INTERRUPTED
|
|
assert run.finished_at is not None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_completed_runs_are_left_alone(self, db):
|
|
async with monitor_db.get_session() as session:
|
|
now = get_current_timestamp()
|
|
task = MonitorTask(
|
|
name="t", platform="xhs", mode=MODE_CREATOR, enabled=True,
|
|
interval_minutes=60, max_notes_count=20, enable_comments=True,
|
|
max_comments_count=50, run_timeout_seconds=3600,
|
|
next_run_at=now, last_status="success", created_at=now, updated_at=now,
|
|
)
|
|
session.add(task)
|
|
await session.flush()
|
|
session.add(
|
|
MonitorRun(
|
|
task_id=task.id, trigger="scheduled", status=RUN_SUCCESS,
|
|
phase=MODE_CREATOR, save_data_path="", queued_at=now, not_before=0,
|
|
started_at=now, finished_at=now, max_comments_count=50,
|
|
)
|
|
)
|
|
|
|
await MonitorScheduler().recover()
|
|
|
|
async with monitor_db.get_session() as session:
|
|
run = await session.scalar(select(MonitorRun))
|
|
assert run.status == RUN_SUCCESS
|
|
|
|
|
|
async def _make_run(
|
|
task_id: int, *, started_minutes_ago: int, status: str = RUN_RUNNING
|
|
) -> int:
|
|
now = get_current_timestamp()
|
|
async with monitor_db.get_session() as session:
|
|
run = MonitorRun(
|
|
task_id=task_id,
|
|
trigger="scheduled",
|
|
status=status,
|
|
phase=MODE_CREATOR,
|
|
save_data_path="",
|
|
queued_at=now,
|
|
not_before=0,
|
|
started_at=now - started_minutes_ago * MS_PER_MINUTE,
|
|
max_comments_count=50,
|
|
)
|
|
session.add(run)
|
|
await session.flush()
|
|
return run.id
|
|
|
|
|
|
async def _get_run(run_id: int) -> MonitorRun:
|
|
async with monitor_db.get_session() as session:
|
|
return await session.get(MonitorRun, run_id)
|
|
|
|
|
|
class TestReapStaleRuns:
|
|
"""卡在「运行中」的 run 必须能被周期性地收掉,而不是只能靠重启。
|
|
|
|
``runner`` 那边用 ``asyncio.wait_for(collect(...), timeout=...)`` 兜底,但超时后
|
|
它会去**取消**采集协程、并且**等取消完成**。抖音那条路卡在 Playwright 调用上时
|
|
协程不响应取消,于是 ``except asyncio.TimeoutError`` 根本轮不到 —— 线上真的因此
|
|
挂过 7 条幽灵 run,最久的 48 小时,产物目录全空,只有重启才清掉。
|
|
"""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_past_its_own_timeout_is_reaped(self, db):
|
|
task_id = await _make_task(get_current_timestamp()) # run_timeout_seconds=3600
|
|
run_id = await _make_run(task_id, started_minutes_ago=120)
|
|
|
|
assert await scheduler_module.reap_stale_runs() == 1
|
|
|
|
run = await _get_run(run_id)
|
|
assert run.status == RUN_INTERRUPTED
|
|
assert run.finished_at is not None
|
|
# 留下来的必须是**说得清**的原因,不能是空字符串
|
|
assert "卡死" in (run.error_message or "")
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_still_inside_its_timeout_is_untouched(self, db):
|
|
task_id = await _make_task(get_current_timestamp())
|
|
run_id = await _make_run(task_id, started_minutes_ago=30)
|
|
|
|
assert await scheduler_module.reap_stale_runs() == 0
|
|
assert (await _get_run(run_id)).status == RUN_RUNNING
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_grace_period_leaves_the_runner_time_to_finish(self, db):
|
|
"""刚过超时那一小段不动手 —— 采集那边到点后还要收尾写库。"""
|
|
task_id = await _make_task(get_current_timestamp())
|
|
run_id = await _make_run(task_id, started_minutes_ago=61) # 3600s 刚过
|
|
|
|
assert await scheduler_module.reap_stale_runs() == 0
|
|
assert (await _get_run(run_id)).status == RUN_RUNNING
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_finished_runs_are_left_alone(self, db):
|
|
task_id = await _make_task(get_current_timestamp())
|
|
run_id = await _make_run(task_id, started_minutes_ago=1000, status=RUN_SUCCESS)
|
|
|
|
assert await scheduler_module.reap_stale_runs() == 0
|
|
assert (await _get_run(run_id)).status == RUN_SUCCESS
|