超级编导对密码尝试有次数限制(实测提示今日剩余 4 次)。自动追加失败后每 30 分钟重试一次,密码错的话当天就能把账号锁掉。1002/10006/4026 这类凭据 错误改成 30 天后再试;设置页保存新凭据会把调度钟拨回现在,不会卡住。
480 lines
21 KiB
Python
480 lines
21 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/api/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中的所有条款。
|
||
|
||
"""Background scheduler for monitor tasks.
|
||
|
||
One asyncio loop polls for due tasks and hands them to the runner. A plain loop
|
||
is enough here: there is exactly one process, one global crawler subprocess, and
|
||
therefore no concurrency to coordinate -- a cron-style library would add a
|
||
dependency without adding a capability.
|
||
|
||
Two families of schedule, and the difference matters:
|
||
|
||
* ``interval`` is **fixed-delay**, not fixed-rate -- ``next_run_at`` is measured
|
||
from the moment a run starts, so a slow run cannot make its task fire
|
||
back-to-back.
|
||
* the clock modes (``daily``/``weekly``) are **fixed-time** -- recomputed from the
|
||
calendar, so a run that starts late does not drag every later run with it.
|
||
|
||
The arithmetic for both lives in schedule.py.
|
||
|
||
The loop also carries the 上游更新检查: it is not a crawl, so it shares none of
|
||
the rules above (no subprocess, no active-hours gate) -- see
|
||
``_maybe_check_upstream``. It rides this loop rather than getting a thread of its
|
||
own because it is one HTTP-shaped fetch per day.
|
||
"""
|
||
|
||
import asyncio
|
||
import random
|
||
from datetime import datetime
|
||
from typing import Optional
|
||
|
||
from sqlalchemy import or_, select
|
||
|
||
from tools.time_util import get_current_timestamp
|
||
|
||
from ..services import crawler_manager
|
||
from . import adapters, app_settings, schedule, superdir, upstream
|
||
from .db import get_session
|
||
from .models import (
|
||
MODE_NOTE,
|
||
RUN_INTERRUPTED,
|
||
RUN_PENDING,
|
||
RUN_RUNNING,
|
||
MonitorRun,
|
||
MonitorTask,
|
||
)
|
||
from .runner import execute_task
|
||
from .settings import get_cookie, get_setting, platform_key, set_setting
|
||
|
||
POLL_INTERVAL_SECONDS = 20
|
||
# Spread tasks sharing an interval so they do not all come due on the same tick.
|
||
# Applied to interval mode only -- see the advance step below.
|
||
JITTER_SECONDS = 60
|
||
# 超时之后再等这么久才动手回收。采集那边到点后还要收尾写库,别和它抢。
|
||
REAP_GRACE_SECONDS = 300
|
||
|
||
|
||
def _time_reached(now: datetime, send_at: str) -> bool:
|
||
"""``HH:MM`` 到了没有。
|
||
|
||
配置写错(空串、``"22"``、``"九点"``)时按 09:00 算 —— 一个手滑的配置不该让
|
||
推送永远发不出去。
|
||
"""
|
||
try:
|
||
hour_text, minute_text = send_at.split(":", 1)
|
||
target = (int(hour_text), int(minute_text))
|
||
except (AttributeError, ValueError):
|
||
target = (9, 0)
|
||
return (now.hour, now.minute) >= target
|
||
|
||
|
||
async def reap_stale_runs() -> int:
|
||
"""把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。
|
||
|
||
**为什么不能只靠 ``asyncio.wait_for`` 的超时。** 它超时后会去**取消**采集协程,
|
||
而取消要等协程真正结束。抖音那条路会卡在 Playwright 的调用上
|
||
(``douyin_api._read_browser`` 里 ``playwright.stop()`` 原先没包超时,driver
|
||
一卡就永不返回),这种协程不响应取消 —— 于是 ``wait_for`` 自己也永远不返回,
|
||
``except asyncio.TimeoutError`` 根本轮不到,run 就永远停在「运行中」。
|
||
实测:7 条这样的幽灵,最久的挂了 48 小时,产物目录全空。
|
||
|
||
``recover()`` 只在进程启动时跑一次,进程不重启就没人来收。所以这里按 tick 扫。
|
||
|
||
判据用**任务自己配的** ``run_timeout_seconds``(默认 3600),不是写死时长 ——
|
||
每个任务允许跑多久本来就不一样。
|
||
"""
|
||
now = get_current_timestamp()
|
||
reaped = 0
|
||
async with get_session() as session:
|
||
rows = (
|
||
await session.execute(
|
||
select(MonitorRun, MonitorTask.run_timeout_seconds)
|
||
.join(MonitorTask, MonitorTask.id == MonitorRun.task_id)
|
||
.where(MonitorRun.status == RUN_RUNNING)
|
||
)
|
||
).all()
|
||
for run, timeout_seconds in rows:
|
||
if run.started_at is None:
|
||
continue
|
||
limit_ms = (
|
||
max(1, int(timeout_seconds or 3600)) + REAP_GRACE_SECONDS
|
||
) * 1000
|
||
if now - run.started_at < limit_ms:
|
||
continue
|
||
run.status = RUN_INTERRUPTED
|
||
run.finished_at = now
|
||
run.error_message = (
|
||
f"超过 {timeout_seconds} 秒仍未结束,已判定为卡死并回收"
|
||
"(采集协程没有响应取消,通常卡在浏览器调用上)"
|
||
)
|
||
reaped += 1
|
||
|
||
if reaped:
|
||
print(
|
||
f"[monitor.scheduler] 回收了 {reaped} 个卡死的 run(超过各自超时仍未结束)",
|
||
flush=True,
|
||
)
|
||
return reaped
|
||
|
||
|
||
class MonitorScheduler:
|
||
"""Polls the task table and runs whatever is due."""
|
||
|
||
def __init__(self) -> None:
|
||
self._loop_task: Optional[asyncio.Task] = None
|
||
self._stopping = asyncio.Event()
|
||
# Avoids logging "no cookie" on every single tick. Per platform, because
|
||
# warning once for Xiaohongshu must not silence the warning for Douyin.
|
||
self._warned_no_cookie: set = set()
|
||
# 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。
|
||
self._superdir_task: Optional[asyncio.Task] = None
|
||
|
||
async def start(self) -> None:
|
||
if self._loop_task is not None and not self._loop_task.done():
|
||
return
|
||
self._stopping.clear()
|
||
self._loop_task = asyncio.create_task(self._run_loop())
|
||
|
||
async def stop(self) -> None:
|
||
self._stopping.set()
|
||
if self._loop_task is not None:
|
||
self._loop_task.cancel()
|
||
try:
|
||
await self._loop_task
|
||
except asyncio.CancelledError:
|
||
pass
|
||
self._loop_task = None
|
||
|
||
async def _run_loop(self) -> None:
|
||
try:
|
||
await self.recover()
|
||
except Exception as exc: # pragma: no cover - defensive
|
||
print(f"[monitor.scheduler] recovery failed: {exc}")
|
||
|
||
while not self._stopping.is_set():
|
||
# 先收尸再调度:卡死的 run 不该继续占着界面的「运行中」,也不该让
|
||
# 它的任务看起来还在跑。见 reap_stale_runs 的说明。
|
||
try:
|
||
await reap_stale_runs()
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] stale run reap failed: {exc}")
|
||
try:
|
||
await self.tick()
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] tick failed: {exc}")
|
||
# 独立于采集任务,因此单独一段 try:上游检查失败不该影响采集调度,
|
||
# 反过来也一样。
|
||
try:
|
||
await self._maybe_check_upstream()
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] upstream check failed: {exc}")
|
||
# 每日推送和采集、上游检查互不相干,各占一段 try。
|
||
try:
|
||
await self._maybe_send_digest()
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] daily digest failed: {exc}")
|
||
# 超级编导自动追加。和采集、推送都无关,单独一段 try。
|
||
try:
|
||
await self._maybe_sync_superdir()
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] 超级编导自动追加失败: {exc}")
|
||
await asyncio.sleep(POLL_INTERVAL_SECONDS)
|
||
|
||
async def _maybe_sync_superdir(self) -> None:
|
||
"""到点的任务补一批超级编导新发布的作品。
|
||
|
||
**放到后台任务里跑**:它要发第三方接口的请求(慢的时候一次好几秒),
|
||
堵在调度循环里会推迟其他任务的采集。上一次还没跑完就跳过这一 tick ——
|
||
不需要排队,下一次自然还会来。
|
||
"""
|
||
if self._superdir_task is not None and not self._superdir_task.done():
|
||
return
|
||
self._superdir_task = asyncio.create_task(self._sync_superdir())
|
||
|
||
async def _sync_superdir(self) -> None:
|
||
try:
|
||
now = get_current_timestamp()
|
||
async with get_session() as session:
|
||
due = list(
|
||
await session.scalars(
|
||
select(MonitorTask.id).where(
|
||
MonitorTask.platform == adapters.PLATFORM_DY,
|
||
MonitorTask.mode == MODE_NOTE,
|
||
MonitorTask.superdir_auto_enabled.is_(True),
|
||
or_(
|
||
MonitorTask.superdir_auto_next_at.is_(None),
|
||
MonitorTask.superdir_auto_next_at <= now,
|
||
),
|
||
)
|
||
)
|
||
)
|
||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||
print(f"[monitor.scheduler] 读取超级编导自动追加任务失败: {exc}")
|
||
return
|
||
|
||
for task_id in due:
|
||
await self._sync_one_superdir(task_id)
|
||
|
||
async def _sync_one_superdir(self, task_id: int) -> None:
|
||
async with get_session() as session:
|
||
task = await session.get(MonitorTask, task_id)
|
||
if task is None or not task.superdir_auto_enabled:
|
||
return
|
||
try:
|
||
result = await superdir.sync_task(session, task)
|
||
except Exception as exc:
|
||
# 失败**不推** last_at:接口挂了一小时,恢复后这一小时的作品还在
|
||
# 查询窗口里。只把调度钟往后挪。挪多久看错误类型 —— 账号密码错了
|
||
# 就几乎等于「等人来修」,继续每 30 分钟试一次会把号锁掉。
|
||
task.superdir_auto_last_error = str(exc)[:500]
|
||
task.superdir_auto_next_at = (
|
||
get_current_timestamp() + superdir.retry_delay_ms(exc)
|
||
)
|
||
print(
|
||
f"[monitor.scheduler] 超级编导自动追加失败 task={task_id}: {exc}"
|
||
)
|
||
return
|
||
if result["added"]:
|
||
print(
|
||
f"[monitor.scheduler] 超级编导自动追加 task={task_id} "
|
||
f"新增 {result['added']} 条(共 {result['total']})"
|
||
)
|
||
|
||
async def _maybe_check_upstream(self) -> None:
|
||
"""到点就 fetch 一次上游仓库,看它有没有新提交。
|
||
|
||
与采集任务的三条规则都不同,各有理由:它不碰浏览器、也不占采集子进程,
|
||
所以不看 ``is_busy``;它只发一个 git 请求,没有被平台风控的风险,所以也不
|
||
受活跃时段限制 —— 定时检查放在半夜反而是最合适的。
|
||
"""
|
||
async with get_session() as session:
|
||
if not await app_settings.get_value(
|
||
session, "upstream_check_enabled", fallback=False
|
||
):
|
||
return
|
||
interval_minutes = int(
|
||
await app_settings.get_value(
|
||
session, "upstream_check_interval_minutes", fallback=1440
|
||
)
|
||
)
|
||
state = await upstream.load_state(session)
|
||
|
||
checked_at = int(state.get("checked_at") or 0)
|
||
now = get_current_timestamp()
|
||
# 失败也会写 checked_at,所以不通的时候同样是每个间隔重试一次,
|
||
# 而不是每个 tick(20 秒)都去撞一次墙。
|
||
if checked_at and now - checked_at < max(1, interval_minutes) * 60_000:
|
||
return
|
||
|
||
result = await upstream.run_check()
|
||
if result.get("behind"):
|
||
print(
|
||
f"[monitor.scheduler] 上游 {result.get('branch')} 领先 "
|
||
f"{result['behind']} 个提交"
|
||
)
|
||
elif not result.get("ok"):
|
||
print(f"[monitor.scheduler] 上游检查失败:{result.get('error')}")
|
||
|
||
async def _maybe_send_digest(self) -> None:
|
||
"""到点推一张**昨天**的视频情况图到企业微信。
|
||
|
||
每个平台独立配置。**按「这一天发过没有」判断,而不是按「距上次多久」** ——
|
||
进程重启、tick 抖动都不会让它重复推;记的是被报的那一天,不是发送时刻,
|
||
所以早上九点失败、十点补发成功之后,十一点的 tick 不会再发一遍。
|
||
"""
|
||
from . import adapters, digest
|
||
|
||
now = datetime.now()
|
||
# 和 send_daily_digest 走同一个口径,免得「配置说昨天、发出去是今天」。
|
||
target_day = digest.default_day()
|
||
marker = target_day.isoformat()
|
||
|
||
for platform in (adapters.PLATFORM_DY, adapters.PLATFORM_XHS):
|
||
async with get_session() as session:
|
||
if not await app_settings.get_value(
|
||
session, "daily_digest_enabled", platform, False
|
||
):
|
||
continue
|
||
send_at = str(
|
||
await app_settings.get_value(
|
||
session, "daily_digest_time", platform, "09:00"
|
||
)
|
||
).strip()
|
||
last_sent = await get_setting(
|
||
session, platform_key(platform, "daily_digest_last_sent")
|
||
)
|
||
|
||
if last_sent == marker or not _time_reached(now, send_at):
|
||
continue
|
||
|
||
async with get_session() as session:
|
||
ok, detail, count = await digest.send_daily_digest(
|
||
session, platform, target_day
|
||
)
|
||
|
||
if ok:
|
||
async with get_session() as session:
|
||
await set_setting(
|
||
session, platform_key(platform, "daily_digest_last_sent"), marker
|
||
)
|
||
print(
|
||
f"[monitor.scheduler] 已推送 {platform} {marker} 的视频情况图"
|
||
f"({count} 条)",
|
||
flush=True,
|
||
)
|
||
else:
|
||
# 不写 last_sent:下一拍还会重试,直到发出去为止。
|
||
print(
|
||
f"[monitor.scheduler] 视频情况图发送失败({platform},{marker}):"
|
||
f"{detail}",
|
||
flush=True,
|
||
)
|
||
|
||
async def recover(self) -> None:
|
||
"""Clean up state left behind by a server restart.
|
||
|
||
A run still marked ``running`` cannot be running -- its subprocess died
|
||
with the previous process. Marking it interrupted stops it from blocking
|
||
the UI as a phantom in-flight run.
|
||
|
||
**``pending`` 同样是残留**:那一行是上一轮建的,可它后面的采集根本没机会开始
|
||
(进程被重启,或者采集那条路抛了异常),所以它永远不会自己往前走。只清 running
|
||
的话,它会永远挂在界面上显示「排队中」—— 用户看到的就是任务卡住了。
|
||
"""
|
||
async with get_session() as session:
|
||
stale = (
|
||
await session.scalars(
|
||
select(MonitorRun).where(
|
||
MonitorRun.status.in_((RUN_RUNNING, RUN_PENDING))
|
||
)
|
||
)
|
||
).all()
|
||
for run in stale:
|
||
run.status = RUN_INTERRUPTED
|
||
run.finished_at = get_current_timestamp()
|
||
if stale:
|
||
print(
|
||
f"[monitor.scheduler] marked {len(stale)} interrupted run(s) "
|
||
f"left over from a previous process"
|
||
)
|
||
|
||
async def tick(self) -> None:
|
||
"""Run one due task, if the crawler is free and we are in the active window."""
|
||
# The crawler subprocess is a global singleton, so a manual crawl and a
|
||
# monitor run cannot overlap. Returning without advancing next_run_at
|
||
# leaves the task due, and it is picked up on a later tick.
|
||
if crawler_manager.is_busy():
|
||
return
|
||
|
||
async with get_session() as session:
|
||
if not await self._within_active_hours(session):
|
||
# Deliberately does not advance next_run_at: the task simply runs
|
||
# when the window next opens, rather than being skipped for a day.
|
||
return
|
||
|
||
await self._run_due_task()
|
||
|
||
async def _within_active_hours(self, session) -> bool:
|
||
"""Whether scheduled runs are allowed right now (local time)."""
|
||
start, end = await app_settings.active_hours(session)
|
||
hour = datetime.now().hour
|
||
if start <= end:
|
||
return start <= hour <= end
|
||
# Window wraps past midnight, e.g. 22 -> 6.
|
||
return hour >= start or hour <= end
|
||
|
||
async def _run_due_task(self) -> None:
|
||
async with get_session() as session:
|
||
task = await session.scalar(
|
||
select(MonitorTask)
|
||
.where(
|
||
MonitorTask.enabled.is_(True),
|
||
MonitorTask.next_run_at.is_not(None),
|
||
MonitorTask.next_run_at <= get_current_timestamp(),
|
||
)
|
||
.order_by(MonitorTask.next_run_at)
|
||
.limit(1)
|
||
)
|
||
|
||
if task is None:
|
||
return
|
||
|
||
# 没有 cookie 就跳过,是为了不让任务每轮白跑一趟出个认证失败。任务留在
|
||
# due 状态而不推进 —— 用户一粘上 cookie 它就能自己跑起来。
|
||
#
|
||
# **但开着 CDP 时必须放行**:那种模式下登录态来自被接管的那个浏览器,
|
||
# 粘不粘 cookie 根本轮不到它决定成败。不放行的话,选了「接管已有 Chrome」
|
||
# 却没粘 cookie 的用户会发现任务永远不被触发,而且什么错都不报。
|
||
cookie = await get_cookie(session, task.platform)
|
||
if not cookie:
|
||
cdp_enabled = await app_settings.get_value(
|
||
session, "cdp_enabled", fallback=False
|
||
)
|
||
if not cdp_enabled:
|
||
if task.platform not in self._warned_no_cookie:
|
||
print(
|
||
f"[monitor.scheduler] no {task.platform} cookie configured; "
|
||
"scheduled tasks will not run until one is set or CDP is enabled"
|
||
)
|
||
self._warned_no_cookie.add(task.platform)
|
||
return
|
||
self._warned_no_cookie.discard(task.platform)
|
||
|
||
# Advance before running so a crash mid-run cannot cause an immediate
|
||
# re-fire, and so a long outage coalesces into a single run instead
|
||
# of one run per missed interval.
|
||
now = get_current_timestamp()
|
||
following = schedule.next_occurrence(
|
||
mode=task.schedule_mode,
|
||
interval_minutes=task.interval_minutes,
|
||
hours=schedule.parse_hours(task.schedule_hours),
|
||
days=schedule.parse_days(task.schedule_days),
|
||
minute=task.schedule_minute,
|
||
after_ms=now,
|
||
)
|
||
|
||
if following is None:
|
||
# A clock schedule with no times can never fire. The API rejects
|
||
# that shape, so this guards against a hand-edited row: park the
|
||
# task with no next run rather than leaving it permanently due and
|
||
# re-running it on every tick.
|
||
task.next_run_at = None
|
||
print(
|
||
f"[monitor.scheduler] task {task.id} has no usable schedule "
|
||
f"and will not run until one is set"
|
||
)
|
||
elif task.schedule_mode == schedule.MODE_INTERVAL:
|
||
# Jitter belongs to the interval mode only. Spreading identical
|
||
# intervals apart is the point; nudging a time the operator
|
||
# explicitly picked is not -- it just looks like a broken clock.
|
||
task.next_run_at = following + random.randint(0, JITTER_SECONDS) * 1000
|
||
else:
|
||
task.next_run_at = following
|
||
|
||
task_id = task.id
|
||
|
||
try:
|
||
await execute_task(task_id, trigger="scheduled")
|
||
except Exception as exc:
|
||
print(f"[monitor.scheduler] task {task_id} failed: {exc}")
|
||
|
||
|
||
# Global singleton, mirroring the crawler_manager pattern.
|
||
monitor_scheduler = MonitorScheduler()
|