mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-27 14:22:35 +08:00
feat(scheduler): add plugin one-shot job API to host scheduler
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
committed by
InfinityPacer
parent
45322c25fd
commit
b387484395
@@ -168,6 +168,38 @@ def remove_plugin_job(plugin_id: str) -> None:
|
||||
get_scheduler().remove_plugin_job(plugin_id)
|
||||
|
||||
|
||||
def add_plugin_once_job(
|
||||
plugin_id: str,
|
||||
job_id: str,
|
||||
func: Callable[..., Any],
|
||||
name: str,
|
||||
delay_seconds: float = 0,
|
||||
func_kwargs: Optional[dict[str, Any]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
在宿主调度器追加插件一次性任务,替代插件自建 BackgroundScheduler。
|
||||
|
||||
不重建该插件 get_service() 声明的周期服务;同 ID 重复追加时替换未执行的旧任务。
|
||||
:return: 调度器运行中且注册成功时返回 True
|
||||
"""
|
||||
return cast(
|
||||
bool,
|
||||
get_scheduler().add_plugin_once_job(
|
||||
plugin_id,
|
||||
job_id,
|
||||
func,
|
||||
name,
|
||||
delay_seconds=delay_seconds,
|
||||
func_kwargs=func_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def remove_plugin_once_job(plugin_id: str, job_id: str) -> None:
|
||||
"""取消插件尚未执行的一次性任务。"""
|
||||
get_scheduler().remove_plugin_once_job(plugin_id, job_id)
|
||||
|
||||
|
||||
def start_agent_task(task_id: int) -> bool:
|
||||
"""立即执行 Agent 自主定时任务。"""
|
||||
return cast(bool, get_scheduler().start_agent_task(task_id))
|
||||
|
||||
@@ -32,6 +32,7 @@ if TYPE_CHECKING:
|
||||
_build_mediaserver_sync_schedules: Callable[..., Any]
|
||||
_build_progress_callback: Callable[..., Any]
|
||||
_cancel_handle: Callable[[SchedulerHandle], None]
|
||||
_detach_live_plugin_once_jobs: Callable[[str], dict[str, dict[str, Any]]]
|
||||
_finish_job: Callable[..., Any]
|
||||
_finish_unsubmitted_job: Callable[..., None]
|
||||
_format_time: Callable[..., str]
|
||||
|
||||
@@ -13,6 +13,7 @@ from app.scheduler.catalog import SchedulerCatalogOwner
|
||||
from app.scheduler.execution import SchedulerExecutionOwner
|
||||
from app.scheduler.lifecycle import SchedulerLifecycleOwner
|
||||
from app.scheduler.maintenance import SchedulerMaintenanceOwner
|
||||
from app.scheduler.oncejob import SchedulerPluginOnceJobOwner
|
||||
from app.scheduler.progress import SchedulerProgressOwner
|
||||
from app.scheduler.reconcile import SchedulerReconcileOwner
|
||||
from app.scheduler.registry import ExecutionRegistry
|
||||
@@ -32,6 +33,7 @@ def _public_handler(handler: _Handler) -> _Handler:
|
||||
class Scheduler(
|
||||
SchedulerLifecycleOwner,
|
||||
SchedulerReconcileOwner,
|
||||
SchedulerPluginOnceJobOwner,
|
||||
SchedulerBridgeOwner,
|
||||
SchedulerProgressOwner,
|
||||
SchedulerExecutionOwner,
|
||||
|
||||
140
app/scheduler/oncejob.py
Normal file
140
app/scheduler/oncejob.py
Normal file
@@ -0,0 +1,140 @@
|
||||
"""插件一次性任务:在宿主调度器上追加、取消与回收插件的延迟单次执行。"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from apscheduler.jobstores.base import JobLookupError
|
||||
from apscheduler.triggers.date import DateTrigger
|
||||
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.application.scheduling import JobSpec
|
||||
from app.runtime.log import logger, wrap_for_plugin_instance
|
||||
from app.scheduler.contract import _SchedulerOwnerBase
|
||||
|
||||
# 插件一次性任务在运行时 job ID 中的命名段,避免与 get_service() 声明的服务 ID 冲突。
|
||||
PLUGIN_ONCE_JOB_SEGMENT = "once"
|
||||
|
||||
|
||||
class SchedulerPluginOnceJobOwner(_SchedulerOwnerBase):
|
||||
"""插件一次性任务的注册、取消和随插件实例的清理。"""
|
||||
|
||||
@staticmethod
|
||||
def _get_plugin_once_job_id(pid: str, job_id: str) -> str:
|
||||
"""生成插件一次性任务的运行时 job ID。"""
|
||||
return f"{pid}_{PLUGIN_ONCE_JOB_SEGMENT}_{job_id}"
|
||||
|
||||
def add_plugin_once_job(
|
||||
self,
|
||||
pid: str,
|
||||
job_id: str,
|
||||
func: Callable[..., Any],
|
||||
name: str,
|
||||
delay_seconds: float = 0,
|
||||
func_kwargs: Optional[dict[str, Any]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
为插件追加一个延迟执行一次的任务,不影响该插件 get_service() 声明的周期服务。
|
||||
|
||||
任务复用宿主线程池、执行状态、进度和插件实例日志上下文;同一插件内同 ID
|
||||
重复追加时替换尚未执行的旧任务。插件卸载时随 remove_plugin_job(pid) 清除;
|
||||
插件重载换成新实例后,旧实例追加的任务在服务重建时丢弃,不会回调已停止的实例。
|
||||
:param pid: 插件 ID
|
||||
:param job_id: 插件内唯一的任务 ID,不得包含 "|"
|
||||
:param func: 执行函数,通常是插件实例的绑定方法
|
||||
:param name: 仪表盘显示的任务名称
|
||||
:param delay_seconds: 延迟秒数,0 表示尽快执行
|
||||
:param func_kwargs: 传给执行函数的关键字参数
|
||||
:return: 调度器运行中且注册成功时返回 True
|
||||
"""
|
||||
if not pid or not job_id or "|" in job_id:
|
||||
logger.error(f"插件一次性任务 ID 无效:{pid} - {job_id}")
|
||||
return False
|
||||
runtime_id = self._get_plugin_once_job_id(pid, job_id)
|
||||
with self._lock:
|
||||
if not self._scheduler or not self._accepting_submissions():
|
||||
logger.warning(f"调度器未运行,无法注册插件一次性任务:{pid} - {name}")
|
||||
return False
|
||||
self._prune_plugin_once_jobs(pid)
|
||||
self._remove_scheduled_job(runtime_id)
|
||||
plugin_manager = get_plugin_manager()
|
||||
job = JobSpec(
|
||||
runtime_id,
|
||||
name,
|
||||
wrap_for_plugin_instance(func, pid),
|
||||
f"plugin:{pid}",
|
||||
kwargs=func_kwargs or {},
|
||||
).to_runtime_state()
|
||||
self._assign_job_generation(runtime_id, job)
|
||||
job.update(
|
||||
pid=pid,
|
||||
# 插件未运行时读不到名称,用插件 ID 兜底,避免仪表盘和日志显示 None
|
||||
provider_name=plugin_manager.get_plugin_attr(pid, "plugin_name") or pid,
|
||||
once=True,
|
||||
# func 是插件传入的任意可调用对象,只有绑定方法才带 __self__;
|
||||
# 记录注册实例,供服务重建时丢弃已被替换实例的遗留任务。
|
||||
_plugin_instance=getattr(func, "__self__", None),
|
||||
)
|
||||
self._jobs[runtime_id] = job
|
||||
run_date = datetime.now(self._scheduler.timezone) + timedelta(seconds=max(delay_seconds, 0))
|
||||
try:
|
||||
self._scheduler.add_job(
|
||||
self.start,
|
||||
DateTrigger(run_date=run_date),
|
||||
id=runtime_id,
|
||||
name=name,
|
||||
kwargs={"job_id": runtime_id},
|
||||
# 调度线程繁忙导致的延迟不应让一次性任务被静默丢弃。
|
||||
misfire_grace_time=None,
|
||||
replace_existing=True,
|
||||
)
|
||||
except Exception as e:
|
||||
self._jobs.pop(runtime_id, None)
|
||||
logger.error(f"注册插件一次性任务失败:{pid} - {name} - {str(e)}")
|
||||
return False
|
||||
logger.info(f"注册插件一次性任务:{job['provider_name']} - {name},{delay_seconds} 秒后执行")
|
||||
return True
|
||||
|
||||
def remove_plugin_once_job(self, pid: str, job_id: str) -> None:
|
||||
"""取消插件尚未执行的一次性任务;已在运行的任务不会被中断。"""
|
||||
self.remove_plugin_job(pid, self._get_plugin_once_job_id(pid, job_id))
|
||||
|
||||
def _remove_scheduled_job(self, runtime_id: str) -> None:
|
||||
"""从 APScheduler 移除指定 job,不存在时忽略。"""
|
||||
try:
|
||||
self._scheduler.remove_job(runtime_id)
|
||||
except JobLookupError:
|
||||
pass
|
||||
|
||||
def _is_plugin_once_job_pending(self, runtime_id: str, job: dict[str, Any]) -> bool:
|
||||
"""判断一次性任务是否仍待执行或正在执行;已执行完的状态可以回收。"""
|
||||
return (
|
||||
self._scheduler.get_job(runtime_id) is not None
|
||||
or self._is_job_active(runtime_id)
|
||||
or bool(job.get("running"))
|
||||
)
|
||||
|
||||
def _prune_plugin_once_jobs(self, pid: str) -> None:
|
||||
"""回收插件已执行完的一次性任务状态,避免 _jobs 随不同任务 ID 累积。"""
|
||||
for runtime_id, job in list(self._jobs.items()):
|
||||
if job.get("once") and job.get("pid") == pid and not self._is_plugin_once_job_pending(runtime_id, job):
|
||||
self._jobs.pop(runtime_id, None)
|
||||
|
||||
def _detach_live_plugin_once_jobs(self, pid: str) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
取出服务重建时应保留的一次性任务。
|
||||
|
||||
保存配置时宿主先调用 init_plugin 再重建服务,init_plugin 里刚追加的任务必须保留;
|
||||
注册实例已被重载替换或插件已停止运行时,遗留任务随其余服务一起移除。
|
||||
"""
|
||||
once_jobs = [
|
||||
(runtime_id, job) for runtime_id, job in self._jobs.items() if job.get("once") and job.get("pid") == pid
|
||||
]
|
||||
if not once_jobs:
|
||||
return {}
|
||||
current = get_plugin_manager().running_plugins.get(pid)
|
||||
kept: dict[str, dict[str, Any]] = {}
|
||||
for runtime_id, job in once_jobs:
|
||||
instance = job.get("_plugin_instance")
|
||||
if (instance is None or instance is current) and self._is_plugin_once_job_pending(runtime_id, job):
|
||||
kept[runtime_id] = self._jobs.pop(runtime_id)
|
||||
return kept
|
||||
@@ -408,8 +408,11 @@ class SchedulerReconcileOwner(_SchedulerOwnerBase):
|
||||
"""
|
||||
if not self._scheduler or not pid:
|
||||
return
|
||||
# 移除该插件的全部服务
|
||||
self.remove_plugin_job(pid)
|
||||
# 移除该插件的全部服务,仍有效的一次性任务不受周期服务重建影响
|
||||
with self._lock:
|
||||
live_once_jobs = self._detach_live_plugin_once_jobs(pid)
|
||||
self.remove_plugin_job(pid)
|
||||
self._jobs.update(live_once_jobs)
|
||||
# 获取插件服务列表
|
||||
with self._lock:
|
||||
plugin_manager = get_plugin_manager()
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""插件可使用的窄调度服务门面。"""
|
||||
|
||||
from app.application.scheduling import (
|
||||
add_plugin_once_job,
|
||||
get_agent_task_next_run,
|
||||
list_scheduler_jobs,
|
||||
remove_agent_task_job,
|
||||
remove_plugin_job,
|
||||
remove_plugin_once_job,
|
||||
start_agent_task,
|
||||
start_scheduler_job,
|
||||
update_agent_task_job,
|
||||
@@ -15,10 +17,12 @@ from app.schemas.dashboard import ScheduleInfo, ScheduleProgress
|
||||
__all__ = [
|
||||
"ScheduleInfo",
|
||||
"ScheduleProgress",
|
||||
"add_plugin_once_job",
|
||||
"get_agent_task_next_run",
|
||||
"list_scheduler_jobs",
|
||||
"remove_agent_task_job",
|
||||
"remove_plugin_job",
|
||||
"remove_plugin_once_job",
|
||||
"start_agent_task",
|
||||
"start_scheduler_job",
|
||||
"update_agent_task_job",
|
||||
|
||||
@@ -301,7 +301,9 @@ sequenceDiagram
|
||||
- **Scheduler 同名职责包**:旧 `app/scheduler.py` 单体已退役;`catalog.py` 负责作业目录和计划投影,
|
||||
`execution.py`、`bridge.py`、`progress.py` 分别负责执行、跨循环句柄和进度终态,`registry.py`
|
||||
唯一持有 generation、active generation、reservation 与 handle,`reconcile.py` 和 `lifecycle.py`
|
||||
分别负责动态任务协调与启动/重载/关闭。
|
||||
分别负责动态任务协调与启动/重载/关闭,`oncejob.py` 承接插件一次性任务:插件经
|
||||
`app.sdk.scheduler.add_plugin_once_job` 在宿主调度器追加延迟单次执行,不再自建常驻
|
||||
`BackgroundScheduler`;追加不重建周期服务,服务重建只丢弃已被重载替换实例登记的任务。
|
||||
- **Scheduler 显式装配**:`startup/initializers/scheduler.py` 构造业务 Chain 一次,将绑定 callable
|
||||
组成 frozen `SchedulerServices` 后注入 Scheduler;Scheduler 包内不再构造业务 Chain。
|
||||
`app.scheduler` 包根只惰性保留 `Scheduler`/`SchedulerChain` 旧 ABI,新插件经 `app.sdk.scheduler`
|
||||
@@ -760,8 +762,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1051 |
|
||||
| 内部导入边 | 8,921 |
|
||||
| Python 模块 | 1052 |
|
||||
| 内部导入边 | 8,930 |
|
||||
| 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 53(债务已清零,53 条精确 containment) |
|
||||
@@ -771,7 +773,7 @@ flowchart LR
|
||||
| Model/Oper 自动事务与自建 Session | 0 |
|
||||
| 组合根外 `SystemConfigOper()` | 0 |
|
||||
|
||||
整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;宿主依赖边现为 8,921,音乐交互包未新增 SCC。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。当前 `app.startup.lifecycle` 为 572、`app.factory` 为 584、`app.main` 为 586。性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。
|
||||
整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;宿主依赖边现为 8,930,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。当前 `app.startup.lifecycle` 为 573、`app.factory` 为 585、`app.main` 为 587。性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。
|
||||
|
||||
架构专项验证分为两个 CI 投影:`Check event semantic policy` 先运行依赖、Adapter、出口和 Event
|
||||
语义门禁,`Check host architecture snapshot` 再执行快照测试及一次
|
||||
|
||||
@@ -94,7 +94,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁
|
||||
|
||||
| 指标 | 当前值 | 解释 |
|
||||
|---|---:|---|
|
||||
| 宿主 Python 模块 / 内部依赖边 | 1051 / 8,921 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 |
|
||||
| 宿主 Python 模块 / 内部依赖边 | 1052 / 8,930 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 |
|
||||
| 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 |
|
||||
| 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 |
|
||||
| Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 |
|
||||
|
||||
@@ -1097,8 +1097,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 8921,
|
||||
"edge_sha256": "e34590c0ec863317ddeec72b19cd935a13b48e51bd56b31f5a3aae93f26a4953",
|
||||
"edge_count": 8930,
|
||||
"edge_sha256": "54d148d934657cd03ad7c96c6e127bba632b803ac1fb82baa183ba219e2bc47f",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -8753,6 +8753,7 @@
|
||||
"app.scheduler.facade -> app.scheduler.execution",
|
||||
"app.scheduler.facade -> app.scheduler.lifecycle",
|
||||
"app.scheduler.facade -> app.scheduler.maintenance",
|
||||
"app.scheduler.facade -> app.scheduler.oncejob",
|
||||
"app.scheduler.facade -> app.scheduler.progress",
|
||||
"app.scheduler.facade -> app.scheduler.reconcile",
|
||||
"app.scheduler.facade -> app.scheduler.registry",
|
||||
@@ -8776,6 +8777,14 @@
|
||||
"app.scheduler.maintenance -> app.runtime.log",
|
||||
"app.scheduler.maintenance -> app.scheduler",
|
||||
"app.scheduler.maintenance -> app.scheduler.contract",
|
||||
"app.scheduler.oncejob -> app.application",
|
||||
"app.scheduler.oncejob -> app.application.plugin",
|
||||
"app.scheduler.oncejob -> app.application.plugin.runtime",
|
||||
"app.scheduler.oncejob -> app.application.scheduling",
|
||||
"app.scheduler.oncejob -> app.runtime",
|
||||
"app.scheduler.oncejob -> app.runtime.log",
|
||||
"app.scheduler.oncejob -> app.scheduler",
|
||||
"app.scheduler.oncejob -> app.scheduler.contract",
|
||||
"app.scheduler.progress -> app.application",
|
||||
"app.scheduler.progress -> app.application.scheduling",
|
||||
"app.scheduler.progress -> app.runtime",
|
||||
@@ -10022,7 +10031,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1051,
|
||||
"module_count": 1052,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -10939,6 +10948,7 @@
|
||||
"app.scheduler.facade",
|
||||
"app.scheduler.lifecycle",
|
||||
"app.scheduler.maintenance",
|
||||
"app.scheduler.oncejob",
|
||||
"app.scheduler.progress",
|
||||
"app.scheduler.reconcile",
|
||||
"app.scheduler.registry",
|
||||
|
||||
@@ -10360,6 +10360,11 @@
|
||||
"name": "ScheduleProgress",
|
||||
"target": "app.schemas.dashboard.ScheduleProgress"
|
||||
},
|
||||
{
|
||||
"kind": "import",
|
||||
"name": "add_plugin_once_job",
|
||||
"target": "app.application.scheduling.add_plugin_once_job"
|
||||
},
|
||||
{
|
||||
"kind": "import",
|
||||
"name": "get_agent_task_next_run",
|
||||
@@ -10380,6 +10385,11 @@
|
||||
"name": "remove_plugin_job",
|
||||
"target": "app.application.scheduling.remove_plugin_job"
|
||||
},
|
||||
{
|
||||
"kind": "import",
|
||||
"name": "remove_plugin_once_job",
|
||||
"target": "app.application.scheduling.remove_plugin_once_job"
|
||||
},
|
||||
{
|
||||
"kind": "import",
|
||||
"name": "start_agent_task",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 572,
|
||||
"loaded_app_module_count": 573,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 584,
|
||||
"loaded_app_module_count": 585,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 586,
|
||||
"loaded_app_module_count": 587,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -278,6 +278,7 @@ def test_update_plugin_job_binds_instance_around_service_callback(monkeypatch):
|
||||
owner._jobs = {}
|
||||
owner.start = MagicMock()
|
||||
owner.remove_plugin_job = lambda _pid, job_id=None: None
|
||||
owner._detach_live_plugin_once_jobs = lambda _pid: {}
|
||||
owner._assign_job_generation = lambda _job_id, _job: None
|
||||
|
||||
owner.update_plugin_job("DemoPluginWork")
|
||||
|
||||
176
tests/test_plugin_once_job.py
Normal file
176
tests/test_plugin_once_job.py
Normal file
@@ -0,0 +1,176 @@
|
||||
"""插件一次性任务接口测试。
|
||||
|
||||
覆盖宿主调度器为插件追加一次性任务的合同:不重建周期服务、同 ID 替换、
|
||||
取消与卸载清理、执行后回收状态,以及保存配置和重载时对注册实例的处理。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
|
||||
import app.scheduler.oncejob as oncejob_module
|
||||
import app.scheduler.reconcile as reconcile_module
|
||||
from app.runtime.log import current_plugin_instance_id
|
||||
from app.scheduler.oncejob import SchedulerPluginOnceJobOwner
|
||||
from app.scheduler.reconcile import SchedulerReconcileOwner
|
||||
|
||||
PID = "DemoOncePlugin"
|
||||
|
||||
|
||||
class _Owner(SchedulerReconcileOwner, SchedulerPluginOnceJobOwner):
|
||||
"""按 Scheduler Facade 的组合方式拼装对账与一次性任务两个 owner。"""
|
||||
|
||||
|
||||
class _DemoPlugin:
|
||||
"""按插件实例绑定方法注册任务的最小插件替身。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict] = []
|
||||
self.done = threading.Event()
|
||||
|
||||
def run_once(self, **kwargs) -> None:
|
||||
self.calls.append({"kwargs": kwargs, "instance_id": current_plugin_instance_id()})
|
||||
self.done.set()
|
||||
|
||||
def periodic(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owner(monkeypatch):
|
||||
"""构造使用真实 APScheduler、其余宿主依赖为替身的调度对账 owner。"""
|
||||
plugin = _DemoPlugin()
|
||||
manager = SimpleNamespace(
|
||||
running_plugins={PID: plugin},
|
||||
get_plugin_attr=lambda _pid, _attr: "演示插件",
|
||||
get_plugin_services=lambda pid: [
|
||||
{
|
||||
"id": "periodic",
|
||||
"name": "周期任务",
|
||||
"func": manager.running_plugins[PID].periodic,
|
||||
"trigger": "interval",
|
||||
"kwargs": {"hours": 1},
|
||||
}
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(reconcile_module, "get_plugin_manager", lambda: manager)
|
||||
monkeypatch.setattr(oncejob_module, "get_plugin_manager", lambda: manager)
|
||||
|
||||
scheduler = BackgroundScheduler(timezone="UTC")
|
||||
owner = _Owner.__new__(_Owner)
|
||||
owner._scheduler = scheduler
|
||||
owner._lock = threading.RLock()
|
||||
owner._jobs = {}
|
||||
owner._assign_job_generation = lambda _job_id, job: job.setdefault("_generation", 0)
|
||||
owner._accepting_submissions = lambda: True
|
||||
owner._is_job_active = lambda _job_id: False
|
||||
|
||||
def _start(job_id: str) -> bool:
|
||||
# 真实 start 的准入、进度与收尾由既有调度测试覆盖,这里只执行已登记的函数。
|
||||
job = owner._jobs[job_id]
|
||||
job["func"](**job["kwargs"])
|
||||
return True
|
||||
|
||||
owner.start = _start
|
||||
scheduler.start()
|
||||
owner.plugin = plugin
|
||||
owner.manager = manager
|
||||
yield owner
|
||||
scheduler.shutdown(wait=False)
|
||||
|
||||
|
||||
def _once_id(job_id: str) -> str:
|
||||
return f"{PID}_once_{job_id}"
|
||||
|
||||
|
||||
def test_once_job_runs_with_plugin_context_and_keeps_periodic_jobs(owner) -> None:
|
||||
"""一次性任务按实例上下文执行,且不重建同插件已注册的周期服务。"""
|
||||
owner.update_plugin_job(PID)
|
||||
periodic = owner._scheduler.get_job(f"{PID}_periodic")
|
||||
next_run = periodic.next_run_time
|
||||
|
||||
assert owner.add_plugin_once_job(PID, "refresh", owner.plugin.run_once, "立即刷新", func_kwargs={"force": True})
|
||||
|
||||
assert owner.plugin.done.wait(5)
|
||||
assert owner.plugin.calls == [{"kwargs": {"force": True}, "instance_id": PID}]
|
||||
assert owner._scheduler.get_job(f"{PID}_periodic").next_run_time == next_run
|
||||
assert owner._jobs[_once_id("refresh")]["provider_name"] == "演示插件"
|
||||
|
||||
|
||||
def test_once_job_with_same_id_replaces_pending_one(owner) -> None:
|
||||
"""同 ID 重复追加只保留最后一次注册。"""
|
||||
assert owner.add_plugin_once_job(PID, "shot", owner.plugin.run_once, "截图", delay_seconds=60, func_kwargs={"n": 1})
|
||||
assert owner.add_plugin_once_job(PID, "shot", owner.plugin.run_once, "截图", delay_seconds=60, func_kwargs={"n": 2})
|
||||
|
||||
once_jobs = [job for job in owner._scheduler.get_jobs() if job.id == _once_id("shot")]
|
||||
assert len(once_jobs) == 1
|
||||
assert owner._jobs[_once_id("shot")]["kwargs"] == {"n": 2}
|
||||
|
||||
|
||||
def test_remove_once_job_and_uninstall_cleanup(owner) -> None:
|
||||
"""单个取消只影响目标任务,按插件移除时清掉全部一次性任务。"""
|
||||
owner.add_plugin_once_job(PID, "a", owner.plugin.run_once, "A", delay_seconds=60)
|
||||
owner.add_plugin_once_job(PID, "b", owner.plugin.run_once, "B", delay_seconds=60)
|
||||
|
||||
owner.remove_plugin_once_job(PID, "a")
|
||||
assert owner._scheduler.get_job(_once_id("a")) is None
|
||||
assert _once_id("a") not in owner._jobs
|
||||
assert owner._scheduler.get_job(_once_id("b")) is not None
|
||||
|
||||
owner.remove_plugin_job(PID)
|
||||
assert owner._scheduler.get_job(_once_id("b")) is None
|
||||
assert not owner._jobs
|
||||
|
||||
|
||||
def test_update_plugin_job_keeps_once_jobs_registered_by_current_instance(owner) -> None:
|
||||
"""保存配置时 init_plugin 先追加任务、宿主后重建服务,任务必须保留。"""
|
||||
owner.add_plugin_once_job(PID, "onlyonce", owner.plugin.run_once, "立即运行一次", delay_seconds=60)
|
||||
|
||||
owner.update_plugin_job(PID)
|
||||
|
||||
assert owner._scheduler.get_job(_once_id("onlyonce")) is not None
|
||||
assert _once_id("onlyonce") in owner._jobs
|
||||
assert owner._scheduler.get_job(f"{PID}_periodic") is not None
|
||||
|
||||
|
||||
def test_update_plugin_job_drops_once_jobs_of_replaced_instance(owner) -> None:
|
||||
"""插件重载换成新实例后,旧实例追加的任务不得再回调旧实例。"""
|
||||
owner.add_plugin_once_job(PID, "stale", owner.plugin.run_once, "旧实例任务", delay_seconds=60)
|
||||
owner.manager.running_plugins[PID] = _DemoPlugin()
|
||||
|
||||
owner.update_plugin_job(PID)
|
||||
|
||||
assert owner._scheduler.get_job(_once_id("stale")) is None
|
||||
assert _once_id("stale") not in owner._jobs
|
||||
|
||||
|
||||
def test_finished_once_job_state_is_pruned_on_next_registration(owner) -> None:
|
||||
"""执行完的一次性任务状态在下次追加时回收,不随任务 ID 累积。"""
|
||||
owner.add_plugin_once_job(PID, "first", owner.plugin.run_once, "第一次")
|
||||
assert owner.plugin.done.wait(5)
|
||||
|
||||
owner.add_plugin_once_job(PID, "second", owner.plugin.run_once, "第二次", delay_seconds=60)
|
||||
|
||||
assert _once_id("first") not in owner._jobs
|
||||
assert _once_id("second") in owner._jobs
|
||||
|
||||
|
||||
def test_once_job_provider_falls_back_to_plugin_id(owner) -> None:
|
||||
"""插件名称读不到时用插件 ID 作为提供方,避免显示 None。"""
|
||||
owner.manager.get_plugin_attr = lambda _pid, _attr: None
|
||||
|
||||
assert owner.add_plugin_once_job(PID, "noname", owner.plugin.run_once, "无名称", delay_seconds=60)
|
||||
|
||||
assert owner._jobs[_once_id("noname")]["provider_name"] == PID
|
||||
|
||||
|
||||
def test_once_job_rejected_when_scheduler_not_accepting_or_id_invalid(owner) -> None:
|
||||
"""调度器不再接受提交或任务 ID 非法时返回 False,且不留下状态。"""
|
||||
assert not owner.add_plugin_once_job(PID, "bad|id", owner.plugin.run_once, "非法")
|
||||
owner._accepting_submissions = lambda: False
|
||||
assert not owner.add_plugin_once_job(PID, "late", owner.plugin.run_once, "停机中")
|
||||
assert not owner._jobs
|
||||
@@ -8,10 +8,12 @@ def test_scheduler_sdk_exposes_only_narrow_service_contracts() -> None:
|
||||
assert set(scheduler_sdk.__all__) == {
|
||||
"ScheduleInfo",
|
||||
"ScheduleProgress",
|
||||
"add_plugin_once_job",
|
||||
"get_agent_task_next_run",
|
||||
"list_scheduler_jobs",
|
||||
"remove_agent_task_job",
|
||||
"remove_plugin_job",
|
||||
"remove_plugin_once_job",
|
||||
"start_agent_task",
|
||||
"start_scheduler_job",
|
||||
"update_agent_task_job",
|
||||
|
||||
Reference in New Issue
Block a user