refactor(system): 收口系统 API 业务职责

This commit is contained in:
jxxghp
2026-08-30 12:15:53 +08:00
parent 5cd5780d36
commit d50177f45d
16 changed files with 1222 additions and 619 deletions

View File

@@ -1,31 +1,15 @@
import asyncio
import io
import json
import re
import zipfile
from collections import deque
from datetime import datetime
from pathlib import Path
from typing import Annotated, Any, Optional, Union
from urllib.parse import urlparse
import aiofiles
import anyio
import pillow_avif # noqa: F401 # pylint: disable=unused-import # AVIF 注册副作用
from anyio import Path as AsyncPath
from fastapi import Body, Depends, Header, HTTPException, Request, Response
from fastapi.responses import StreamingResponse
from app.adapters.external.plugin.client import (
PLUGIN_MARKET_WIKI_URL,
extract_plugin_market_repos_from_wiki,
merge_plugin_market_repos,
split_plugin_market_repo_urls,
)
from app.adapters.external.server import MoviePilotServerHelper
from app.adapters.network.http import AsyncRequestUtils, RequestUtils
from app.adapters.system import rust as rust_accel
from app.adapters.system.update import system_update_manager
from app.adapters.web.security.access import verify_apitoken, verify_resource_token, verify_token
from app.api.context import get_host_runtime
from app.api.dependencies.auth import (
@@ -45,11 +29,11 @@ from app.application.image import ImageHelper
from app.application.messaging.message import MessageHelper
from app.application.module import get_module_manager
from app.application.network import get_configured_network_test_service
from app.application.plugin.runtime import plugin_system_config_mutation
from app.application.rules import RuleHelper
from app.application.scheduling import get_scheduler
from app.application.security.url import SecurityUtils
from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module
from app.application.system import LogFileData, LogNotFoundError
from app.chain.media import MediaChain
from app.chain.mediaserver import MediaServerChain
from app.chain.search.facade import SearchChain
@@ -57,22 +41,16 @@ from app.domain.context import TorrentInfo as _DomainTorrentInfo
from app.domain.metainfo import MetaInfo
from app.foundation.crypto import HashUtils
from app.foundation.environment import is_free_threaded_runtime, is_gil_enabled
from app.runtime.events import eventmanager
from app.runtime.execution import run_in_threadpool_to_completion
from app.runtime.localization import LocaleHelper
from app.runtime.log import logger
from app.runtime.progress import AsyncProgressHelper
from app.runtime.scheduling import TimerUtils
from app.runtime.state import SystemHelper
from app.runtime.stop import runtime_stop_state
from app.runtime.version import get_app_version, get_frontend_version
from app.schemas.common import JsonData
from app.schemas.common import JsonObject as _SchemaJsonObject
from app.schemas.common import JsonObjectList as _SchemaJsonObjectList
from app.schemas.common import TimeData as _SchemaTimeData
from app.schemas.common import ValueData as _SchemaValueData
from app.schemas.event import ConfigChangeEventData
from app.schemas.exception import PluginMutationRejectedError
from app.schemas.response import Response as _SchemaResponse
from app.schemas.system import DatabaseBackupArtifactData as _SchemaDatabaseBackupArtifactData
from app.schemas.system import DatabaseBackupVerificationData as _SchemaDatabaseBackupVerificationData
@@ -84,7 +62,7 @@ from app.schemas.system import SystemEnvironmentUpdateData as _SchemaSystemEnvir
from app.schemas.system import SystemModuleListData as _SchemaSystemModuleListData
from app.schemas.system import SystemUpdateStatus as _SchemaSystemUpdateStatus
from app.schemas.token import TokenPayload as _SchemaTokenPayload
from app.schemas.types import EventType, SystemConfigKey
from app.schemas.types import SystemConfigKey
from app.startup.composition.context import HostRuntime
router = ResponseAPIRouter()
@@ -103,16 +81,6 @@ _PUBLIC_SYSTEM_CONFIG_KEYS = {
)
}
_PUBLIC_SETTINGS_KEYS = {"PLUGIN_MARKET"}
_LOG_DOWNLOAD_LIMIT = 10
_LOG_DOWNLOAD_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
_DATABASE_BACKUP_SETTING_KEYS = {
"DB_BACKUP_ENABLE",
"DB_BACKUP_CRON",
"DB_BACKUP_ON_UPGRADE",
"DB_BACKUP_PATH",
"DB_BACKUP_RETENTION_DAYS",
"DB_BACKUP_MAX_COUNT",
}
def _database_backup_artifact_data(artifact: Any) -> _SchemaDatabaseBackupArtifactData:
@@ -125,142 +93,6 @@ def _database_backup_artifact_data(artifact: Any) -> _SchemaDatabaseBackupArtifa
)
def _validate_llm_server_tool_config(env: dict) -> Optional[str]:
"""校验强制服务端联网搜索配置,返回用户可读错误信息。"""
from app.agent.llm.tools import (
ServerToolRegistry,
ServerToolUnavailableError,
)
runtime_settings = get_runtime_settings()
mode = ServerToolRegistry.normalize_web_search_mode(
env.get(
"LLM_WEB_SEARCH_MODE",
runtime_settings.get("LLM_WEB_SEARCH_MODE", "local"),
)
)
if mode != "builtin":
return None
provider = str(
env.get("LLM_PROVIDER", runtime_settings.get("LLM_PROVIDER", "")) or ""
).strip()
model = str(
env.get("LLM_MODEL", runtime_settings.get("LLM_MODEL", "")) or ""
).strip()
base_url = env.get("LLM_BASE_URL", runtime_settings.get("LLM_BASE_URL"))
capability = ServerToolRegistry.get_capability(
provider=provider,
model=model,
base_url=str(base_url or "").strip() or None,
tool_id="web_search",
)
if capability:
return None
return str(
ServerToolUnavailableError(
provider=provider,
model=model,
tool_id="web_search",
)
)
def _validate_database_backup_config(env: dict) -> Optional[str]:
"""在批量写入前校验数据库备份策略,避免只保存部分字段。"""
if not _DATABASE_BACKUP_SETTING_KEYS.intersection(env):
return None
runtime_settings = get_runtime_settings()
cron = str(env.get("DB_BACKUP_CRON", runtime_settings.get("DB_BACKUP_CRON")) or "").strip()
if cron:
try:
TimerUtils.normalize_schedule_trigger(
"cron",
cron,
runtime_settings.get("TZ"),
)
except (TypeError, ValueError):
return "数据库备份周期格式不正确"
backup_path = env.get("DB_BACKUP_PATH", runtime_settings.get("DB_BACKUP_PATH"))
if backup_path is not None and not isinstance(backup_path, str):
return "数据库备份目录必须是路径字符串"
for key, label in (
("DB_BACKUP_RETENTION_DAYS", "数据库备份过期天数"),
("DB_BACKUP_MAX_COUNT", "数据库备份最大保留份数"),
):
value = env.get(key, runtime_settings.get(key))
if isinstance(value, bool):
return f"{label}必须是大于等于 0 的整数"
try:
converted = int(value)
except (TypeError, ValueError):
return f"{label}必须是大于等于 0 的整数"
if converted < 0 or str(value).strip() != str(converted):
return f"{label}必须是大于等于 0 的整数"
return None
def _is_allowed_plugin_market_wiki_url(wiki_url: str) -> bool:
"""
校验插件市场 Wiki 地址是否属于固定文档源。
"""
parsed_url = urlparse(wiki_url)
if parsed_url.scheme != "https":
return False
if (parsed_url.hostname or "").lower() != "raw.githubusercontent.com":
return False
return bool(
re.fullmatch(
r"/jxxghp/MoviePilot-Wiki/[^/]+/plugin\.md",
parsed_url.path,
)
)
def _collect_named_log_files(name: str) -> list[Path]:
"""
根据前端传入的日志标识收集可下载日志文件。
`moviepilot` 固定表示主程序日志,其余标识按插件 ID 处理并映射到
`plugins/<plugin_id>.log*`。这里不接收路径或后缀,避免下载入口变成任意
日志文件选择器;滚动日志按当前文件优先、备份文件按修改时间倒序补足。
"""
normalized_name = (name or "").strip().lower()
if not normalized_name or not _LOG_DOWNLOAD_NAME_PATTERN.fullmatch(normalized_name):
raise HTTPException(status_code=404, detail="Not Found")
log_root = Path(get_runtime_settings().get("LOG_PATH"))
if normalized_name == "moviepilot":
log_dir = log_root
log_prefix = "moviepilot.log"
else:
log_dir = log_root / "plugins"
log_prefix = f"{normalized_name}.log"
if not log_dir.exists() or not log_dir.is_dir():
raise HTTPException(status_code=404, detail="Not Found")
current_log = log_dir / log_prefix
backup_logs = [
item
for item in log_dir.iterdir()
if item.is_file() and item.name.startswith(f"{log_prefix}.")
]
backup_logs.sort(key=lambda item: item.stat().st_mtime, reverse=True)
log_files = []
if current_log.exists() and current_log.is_file():
log_files.append(current_log)
log_files.extend(backup_logs)
return log_files[:_LOG_DOWNLOAD_LIMIT]
def _verify_log_resource_superuser(
token_payload: _SchemaTokenPayload = Depends(verify_resource_token),
) -> _SchemaTokenPayload:
@@ -276,15 +108,17 @@ def _verify_log_resource_superuser(
return token_payload
async def _build_log_zip_response(name: str) -> StreamingResponse:
"""
将指定日志标识对应的日志文件打包为 zip 响应。
打包前逐个校验文件仍位于日志根目录内,避免符号链接或并发文件变更绕过
`name` 到固定目录的映射约束。zip 内使用日志根目录相对路径,便于区分
主程序日志与插件日志。
"""
zip_data, zip_stem = await anyio.to_thread.run_sync(_build_log_zip_data, name)
async def _build_log_zip_response(
name: str, runtime: HostRuntime
) -> StreamingResponse:
"""读取受限日志条目并生成兼容 ZIP 响应。"""
try:
entries = await runtime.system.collect_logs(name)
except LogNotFoundError as error:
raise HTTPException(status_code=404, detail="Not Found") from error
zip_data, zip_stem = await anyio.to_thread.run_sync(
_build_log_zip_data, name, entries
)
headers = {
"Content-Disposition": f'attachment; filename="{zip_stem}.zip"'
}
@@ -295,31 +129,17 @@ async def _build_log_zip_response(name: str) -> StreamingResponse:
)
def _build_log_zip_data(name: str) -> tuple[bytes, str]:
"""
同步生成日志 zip 内容和文件名前缀。
日志收集、路径解析、文件读取和压缩都属于可能阻塞的本地 I/O;调用方需要
将本函数放到 worker thread 中执行,避免日志下载占用 ASGI 事件循环。
"""
log_files = _collect_named_log_files(name)
if not log_files:
raise HTTPException(status_code=404, detail="Not Found")
log_root = Path(get_runtime_settings().get("LOG_PATH"))
def _build_log_zip_data(
name: str, entries: list[LogFileData]
) -> tuple[bytes, str]:
"""只负责把应用服务提供的日志内容编码为 ZIP framing。"""
zip_buffer = io.BytesIO()
filename_time = datetime.now().strftime("%Y%m%d-%H%M%S")
safe_name = (name or "logs").strip().lower() or "logs"
zip_stem = f"{safe_name}-logs-{filename_time}"
with zipfile.ZipFile(zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as archive:
for log_file in log_files:
if not SecurityUtils.is_safe_path(
base_path=log_root,
user_path=log_file,
):
raise HTTPException(status_code=404, detail="Not Found")
arcname = f"{zip_stem}/{log_file.name}"
archive.write(log_file, arcname)
for entry in entries:
archive.writestr(f"{zip_stem}/{entry.name}", entry.content)
zip_buffer.seek(0)
return zip_buffer.getvalue(), zip_stem
@@ -368,7 +188,10 @@ async def fetch_image(
# 检查 If-None-Match
etag = HashUtils.md5(content)
headers = RequestUtils.generate_cache_headers(etag, max_age=86400 * 7)
headers = {
"ETag": etag,
"Cache-Control": f"public, max-age={86400 * 7}",
}
headers["Content-Type"] = media_type
headers["X-Content-Type-Options"] = "nosniff"
if if_none_match == etag:
@@ -498,7 +321,10 @@ def get_global_setting(token: str):
summary="查询用户相关系统设置",
response_model=_SchemaResponse[_SchemaJsonObject],
)
async def get_user_global_setting(_: ApiPrincipal = Depends(get_current_active_user_async)):
async def get_user_global_setting(
_: ApiPrincipal = Depends(get_current_active_user_async),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
查询用户相关系统设置(登录后获取)
包含业务功能相关的配置和用户权限信息
@@ -523,16 +349,13 @@ async def get_user_global_setting(_: ApiPrincipal = Depends(get_current_active_u
info["LLM_SUPPORT_AUDIO_OUTPUT"] = False
# 追加用户唯一ID和订阅分享管理权限
share_admin = await MoviePilotServerHelper.async_is_admin_user()
info.update(
{
"USER_UNIQUE_ID": MoviePilotServerHelper.get_user_uuid(),
"SUBSCRIBE_SHARE_MANAGE": share_admin,
"WORKFLOW_SHARE_MANAGE": share_admin,
"PYTHON_FREE_THREADED": is_free_threaded_runtime(),
"PYTHON_GIL_ENABLED": is_gil_enabled(),
}
)
info.update(await runtime.system.user_global())
return _SchemaResponse(success=True, data=info)
@@ -636,6 +459,7 @@ async def delete_database_backup(
)
async def get_env_setting(
_: ApiPrincipal = Depends(get_current_active_superuser_async),
runtime: HostRuntime = Depends(get_host_runtime),
) -> _SchemaResponse:
"""
查询系统环境变量,包括当前版本号(仅管理员)
@@ -649,14 +473,11 @@ async def get_env_setting(
"AUTH_VERSION": SitesHelper().auth_version,
"INDEXER_VERSION": SitesHelper().indexer_version,
"FRONTEND_VERSION": get_frontend_version(),
"RUST_ACCEL": rust_accel.is_config_enabled(),
"RUST_ACCEL_AVAILABLE": rust_accel.is_available(),
"RUST_ACCEL_ENABLED": rust_accel.is_enabled(),
"RUST_ACCEL_REQUIRED": rust_accel.is_required(),
"PYTHON_FREE_THREADED": is_free_threaded_runtime(),
"PYTHON_GIL_ENABLED": is_gil_enabled(),
}
)
info.update(runtime.system.runtime_features())
return _SchemaResponse(success=True, data=info)
@@ -665,11 +486,14 @@ async def get_env_setting(
summary="查询安装版本统计报表",
response_model=_SchemaResponse[_SchemaJsonObject],
)
async def usage_statistic(_: ApiPrincipal = Depends(get_current_active_user_async)):
async def usage_statistic(
_: ApiPrincipal = Depends(get_current_active_user_async),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
查询安装版本统计报表
"""
return _SchemaResponse(success=True, data=await MoviePilotServerHelper.async_get_usage_statistic())
return _SchemaResponse(success=True, data=await runtime.system.usage())
@router.get("/ping", summary="服务存活检测", response_model=_SchemaResponse[None])
@@ -686,43 +510,18 @@ async def ping(_: ApiPrincipal = Depends(get_current_active_user_async)) -> _Sch
response_model=_SchemaResponse[_SchemaSystemEnvironmentUpdateData],
)
async def set_env_setting(
env: dict, _: ApiPrincipal = Depends(get_current_active_superuser_async)
env: dict,
_: ApiPrincipal = Depends(get_current_active_superuser_async),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
更新系统环境变量(仅管理员)
"""
validation_error = _validate_llm_server_tool_config(env)
if validation_error:
return _SchemaResponse(success=False, message=validation_error)
validation_error = _validate_database_backup_config(env)
if validation_error:
return _SchemaResponse(success=False, message=validation_error)
result = get_runtime_settings().update_many(env)
# 统计成功和失败的结果
success_updates = {k: v for k, v in result.items() if v[0]}
failed_updates = {k: v for k, v in result.items() if v[0] is False}
if failed_updates:
return _SchemaResponse(
success=False,
message=f"{', '.join([v[1] for v in failed_updates.values()])}",
data={"success_updates": success_updates, "failed_updates": failed_updates},
)
if success_updates:
# 发送配置变更事件
await eventmanager.async_send_event(
etype=EventType.ConfigChanged,
data=ConfigChangeEventData(
key=success_updates.keys(), change_type="update"
),
)
result = await runtime.system.update_environment(env)
return _SchemaResponse(
success=True,
message="所有配置项更新成功",
data={"success_updates": success_updates},
success=result.success,
message=result.message,
data=result.data,
)
@@ -793,64 +592,18 @@ async def get_public_setting(
async def sync_plugin_market_from_wiki(
request: Optional[_SchemaPluginMarketSyncRequest] = Body(default=None),
_: ApiPrincipal = Depends(get_current_active_superuser_async),
runtime: HostRuntime = Depends(get_host_runtime),
) -> _SchemaResponse:
"""
从 Wiki 插件文档同步插件市场仓库地址。
"""
wiki_url = (request.wiki_url if request else None) or PLUGIN_MARKET_WIKI_URL
wiki_url = wiki_url.strip()
if not _is_allowed_plugin_market_wiki_url(wiki_url):
return _SchemaResponse(success=False, message="不支持的 Wiki 同步地址")
res = await AsyncRequestUtils(
ua=get_runtime_settings().get("USER_AGENT"),
proxies=get_runtime_settings().get("PROXY"),
timeout=30,
content_type=None,
accept_type="text/plain,*/*",
).get_res(wiki_url)
if res is None:
return _SchemaResponse(success=False, message="无法访问 Wiki 插件仓库清单")
if res.status_code != 200:
return _SchemaResponse(
success=False,
message=f"访问 Wiki 插件仓库清单失败,状态码:{res.status_code}",
)
wiki_repos = extract_plugin_market_repos_from_wiki(res.text)
if not wiki_repos:
return _SchemaResponse(success=False, message="未在 Wiki 中识别到插件仓库地址")
local_repos = split_plugin_market_repo_urls(
get_runtime_settings().get("PLUGIN_MARKET", "")
result = await runtime.system.sync_plugin_market(
request.wiki_url if request else None
)
local_repo_keys = {repo.lower() for repo in local_repos}
added_count = len([repo for repo in wiki_repos if repo.lower() not in local_repo_keys])
merged_repos = merge_plugin_market_repos(local_repos, wiki_repos)
merged_value = ",".join(merged_repos)
success, message = get_runtime_settings().update("PLUGIN_MARKET", merged_value)
if success:
await eventmanager.async_send_event(
etype=EventType.ConfigChanged,
data=ConfigChangeEventData(
key="PLUGIN_MARKET", value=merged_value, change_type="update"
),
)
elif success is None:
success = True
return _SchemaResponse(
success=success,
message=message,
data={
"value": merged_value,
"repos": merged_repos,
"wiki_repos": wiki_repos,
"added_count": added_count,
"total_count": len(merged_repos),
"source_url": wiki_url,
},
success=result.success,
message=result.message,
data=result.data,
)
@@ -883,64 +636,8 @@ async def set_setting(
"""
更新系统设置(仅管理员)
"""
runtime_settings = get_runtime_settings()
if runtime_settings.contains(key):
success, message = runtime_settings.update(key, value)
if success:
# 发送配置变更事件
await eventmanager.async_send_event(
etype=EventType.ConfigChanged,
data=ConfigChangeEventData(key=key, value=value, change_type="update"),
)
elif success is None:
success = True
return _SchemaResponse(success=success, message=message)
elif key in {item.value for item in SystemConfigKey}:
if isinstance(value, list):
value = list(filter(None, value))
value = value if value else None
try:
with plugin_system_config_mutation(key):
event_value: JsonData
if key == SystemConfigKey.UserFilterRuleGroups.value:
current_value = get_configured_system_config().get(
SystemConfigKey.UserFilterRuleGroups
)
expected_definitions = [
dict(item)
for item in current_value or []
if isinstance(item, dict)
] if isinstance(current_value, list) else []
definitions = [
dict(item) for item in value or [] if isinstance(item, dict)
] if isinstance(value, list) else []
async with (
runtime.subscription.async_rule_group_mutation_scope()
) as mutation:
await mutation.apply(
definitions,
expected_rule_groups=expected_definitions,
)
event_value = definitions
success = True
else:
success = await get_configured_system_config().async_set(key, value)
event_value = value
if success:
# 发送配置变更事件
await eventmanager.async_send_event(
etype=EventType.ConfigChanged,
data=ConfigChangeEventData(
key=key,
value=event_value,
change_type="update",
),
)
return _SchemaResponse(success=True)
except PluginMutationRejectedError as error:
return _SchemaResponse(success=False, message=str(error))
else:
return _SchemaResponse(success=False, message=f"配置项 '{key}' 不存在")
result = await runtime.system.update_setting(key, value)
return _SchemaResponse(success=result.success, message=result.message)
@router.get(
@@ -984,112 +681,41 @@ async def _get_logging_impl(
length: Optional[int] = 50,
logfile: Optional[str] = "moviepilot.log",
_: _SchemaTokenPayload = Depends(_verify_log_resource_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
实时获取系统日志
length = -1 时, 返回text/plain
否则 返回格式SSE
"""
base_path = AsyncPath(get_runtime_settings().get("LOG_PATH"))
log_path = base_path / logfile
if not await SecurityUtils.async_is_safe_path(
base_path=base_path, user_path=log_path, allowed_suffixes={".log"}
):
raise HTTPException(status_code=404, detail="Not Found")
if not await log_path.exists() or not await log_path.is_file():
raise HTTPException(status_code=404, detail="Not Found")
async def log_generator():
"""把应用服务提供的日志数据映射为文本或 SSE 响应。"""
resolved_logfile = logfile or "moviepilot.log"
if length == -1:
try:
# 使用固定大小的双向队列来限制内存使用
lines_queue = deque(maxlen=max(length, 50))
# 获取文件大小
file_stat = await log_path.stat()
file_size = file_stat.st_size
return Response(
content=await runtime.system.read_log(resolved_logfile),
media_type="text/plain",
)
except LogNotFoundError as error:
raise HTTPException(status_code=404, detail="Not Found") from error
except Exception as error:
return Response(
content=f"读取日志文件失败: {error}", media_type="text/plain"
)
try:
source = await runtime.system.follow_log(
resolved_logfile, length or 50, request.is_disconnected
)
except LogNotFoundError as error:
raise HTTPException(status_code=404, detail="Not Found") from error
# 读取历史日志
async with aiofiles.open(
log_path, mode="r", encoding="utf-8", errors="replace"
) as f:
# 优化大文件读取策略
if file_size > 100 * 1024:
# 只读取最后100KB的内容
bytes_to_read = min(file_size, 100 * 1024)
position = file_size - bytes_to_read
await f.seek(position)
content = await f.read()
# 找到第一个完整的行
first_newline = content.find("\n")
if first_newline != -1:
content = content[first_newline + 1 :]
else:
# 小文件直接读取全部内容
content = await f.read()
# 按行分割并添加到队列,只保留非空行
lines = [line.strip() for line in content.splitlines() if line.strip()]
# 只取最后N行
for line in lines[-max(length, 50) :]:
lines_queue.append(line)
# 输出历史日志
for line in lines_queue:
async def event_generator():
"""只为原始日志行添加 SSE data framing。"""
try:
async for line in source:
yield f"data: {line}\n\n"
# 实时监听新日志
async with aiofiles.open(
log_path, mode="r", encoding="utf-8", errors="replace"
) as f:
# 移动文件指针到文件末尾,继续监听新增内容
await f.seek(0, 2)
# 记录初始文件大小
initial_stat = await log_path.stat()
initial_size = initial_stat.st_size
# 实时监听新日志,使用更短的轮询间隔
while not runtime_stop_state.is_system_stopped:
if await request.is_disconnected():
break
# 检查文件是否有新内容
current_stat = await log_path.stat()
current_size = current_stat.st_size
if current_size > initial_size:
# 文件有新内容,读取新行
line = await f.readline()
if line:
line = line.strip()
if line:
yield f"data: {line}\n\n"
initial_size = current_size
else:
# 没有新内容,短暂等待
await asyncio.sleep(0.5)
except asyncio.CancelledError:
return
except Exception as err:
logger.error(f"日志读取异常: {err}")
yield f"data: 日志读取异常: {err}\n\n"
except Exception as error:
logger.error("日志读取异常: %s", error)
yield f"data: 日志读取异常: {error}\n\n"
# 根据length参数返回不同的响应
if length == -1:
# 返回全部日志作为文本响应
if not await log_path.exists():
return Response(content="日志文件不存在!", media_type="text/plain")
try:
# 使用 aiofiles 异步读取文件
async with aiofiles.open(
log_path, mode="r", encoding="utf-8", errors="replace"
) as file:
text = await file.read()
# 倒序输出
text = "\n".join(text.split("\n")[::-1])
return Response(content=text, media_type="text/plain")
except Exception as e:
return Response(content=f"读取日志文件失败: {e}", media_type="text/plain")
else:
# 返回SSE流响应
return StreamingResponse(log_generator(), media_type="text/event-stream")
return StreamingResponse(event_generator(), media_type="text/event-stream")
@router.get(
@@ -1104,9 +730,10 @@ async def get_logging(
length: Optional[int] = 50,
logfile: Optional[str] = "moviepilot.log",
_: _SchemaTokenPayload = Depends(_verify_log_resource_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""实时日志的兼容公开入口。"""
return await _get_logging_impl(request, length, logfile, _)
return await _get_logging_impl(request, length, logfile, _, runtime)
@router.get(
@@ -1128,11 +755,12 @@ async def get_logging(
async def download_logging(
name: str,
_: _SchemaTokenPayload = Depends(_verify_log_resource_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
按日志标识下载主程序或插件滚动日志,返回 zip 文件。
"""
return await _build_log_zip_response(name)
return await _build_log_zip_response(name, runtime)
@router.get(
@@ -1140,18 +768,16 @@ async def download_logging(
summary="查询Github所有Release版本",
response_model=_SchemaResponse[_SchemaJsonObjectList],
)
async def latest_version(_: _SchemaTokenPayload = Depends(verify_token)):
async def latest_version(
_: _SchemaTokenPayload = Depends(verify_token),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
查询Github所有Release版本
"""
version_res = await AsyncRequestUtils(
proxies=get_runtime_settings().get("PROXY"),
headers=get_runtime_settings().get("GITHUB_HEADERS"),
).get_res("https://api.github.com/repos/jxxghp/MoviePilot/releases")
if version_res is not None and version_res.status_code == 200:
ver_json = version_res.json()
if ver_json:
return _SchemaResponse(success=True, data=ver_json)
releases = await runtime.system.releases()
if releases:
return _SchemaResponse(success=True, data=releases)
return _SchemaResponse(success=False)
@@ -1320,31 +946,26 @@ def moduletest(moduleid: str, _: _SchemaTokenPayload = Depends(verify_token)):
@router.get("/restart", summary="重启系统", response_model=_SchemaResponse[None])
def restart_system(_: ApiPrincipal = Depends(get_current_active_superuser)):
def restart_system(
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""
重启系统(仅管理员)
"""
if not SystemHelper.can_restart():
return _SchemaResponse(success=False, message="当前运行环境不支持重启操作!")
ret, msg = SystemHelper.restart()
return _SchemaResponse(success=ret, message=msg)
result = runtime.system.restart()
return _SchemaResponse(success=result.success, message=result.message)
@router.post("/upgrade", summary="Dev 更新并重启系统", response_model=_SchemaResponse[None])
def upgrade_system(
mode: Annotated[str | None, Body()] = None,
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""保留 Dev 更新入口;Release 更新必须使用后台下载与确认安装流程。"""
if str(mode or "").strip().lower() != "dev":
return _SchemaResponse(
success=False,
message="Release 更新请使用 /system/update/check、download 和 install 接口",
)
if not SystemHelper.can_restart():
return _SchemaResponse(success=False, message="当前运行环境不支持升级操作!")
success, message = SystemHelper.upgrade_dev()
return _SchemaResponse(success=success, message=message)
result = runtime.system.upgrade(mode)
return _SchemaResponse(success=result.success, message=result.message)
@router.get(
@@ -1354,9 +975,10 @@ def upgrade_system(
)
def system_update_status(
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""返回后台检查、下载或待安装状态(仅管理员)。"""
return _SchemaResponse(success=True, data=system_update_manager.get_status())
return _SchemaResponse(success=True, data=runtime.system.update_status())
@router.post(
@@ -1366,9 +988,10 @@ def system_update_status(
)
def check_system_update(
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""立即查询 GitHub Release(仅管理员)。"""
return _SchemaResponse(success=True, data=system_update_manager.check())
return _SchemaResponse(success=True, data=runtime.system.check_update())
@router.post(
@@ -1378,12 +1001,13 @@ def check_system_update(
)
def download_system_update(
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""启动后台下载并立即返回当前状态(仅管理员)。"""
if not SystemHelper.can_restart():
return _SchemaResponse(success=False, message="当前运行环境不支持升级操作!")
status = system_update_manager.start_download()
return _SchemaResponse(success=status.state != "failed", data=status, message=status.error)
result = runtime.system.download_update()
return _SchemaResponse(
success=result.success, data=result.data, message=result.message
)
@router.post(
@@ -1393,18 +1017,11 @@ def download_system_update(
)
def install_system_update(
_: ApiPrincipal = Depends(get_current_active_superuser),
runtime: HostRuntime = Depends(get_host_runtime),
):
"""确认消费已校验更新包,并重启进入安装阶段(仅管理员)。"""
if not SystemHelper.can_restart():
return _SchemaResponse(success=False, message="当前运行环境不支持升级操作!")
prepared, message = system_update_manager.request_install()
if not prepared:
return _SchemaResponse(success=False, message=message)
ret, msg = SystemHelper.restart()
if not ret:
system_update_manager.cancel_install(msg)
return _SchemaResponse(success=False, message=msg)
return _SchemaResponse(success=True, message=message)
result = runtime.system.install_update()
return _SchemaResponse(success=result.success, message=result.message)
@router.get("/runscheduler", summary="运行服务", response_model=_SchemaResponse[None])

449
app/application/system.py Normal file
View File

@@ -0,0 +1,449 @@
"""系统管理 API 的应用用例与外部能力端口。"""
from __future__ import annotations
import re
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import AbstractAsyncContextManager, AbstractContextManager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Protocol
from urllib.parse import urlparse
from app.application.configuration import RuntimeSettingsService, SystemConfigService
from app.runtime.scheduling import TimerUtils
from app.schemas.common import JsonData
from app.schemas.exception import PluginMutationRejectedError
from app.schemas.system import SystemUpdateStatus
from app.schemas.types import SystemConfigKey
if TYPE_CHECKING:
from app.application.rules import AsyncRuleGroupMutationService
PLUGIN_MARKET_WIKI_URL = (
"https://raw.githubusercontent.com/jxxghp/MoviePilot-Wiki/main/plugin.md"
)
_DATABASE_BACKUP_SETTING_KEYS = {
"DB_BACKUP_ENABLE",
"DB_BACKUP_CRON",
"DB_BACKUP_ON_UPGRADE",
"DB_BACKUP_PATH",
"DB_BACKUP_RETENTION_DAYS",
"DB_BACKUP_MAX_COUNT",
}
class LogNotFoundError(FileNotFoundError):
"""表示请求的日志标识或文件不属于可读取日志集合。"""
@dataclass(frozen=True, slots=True)
class LogFileData:
"""日志归档中的稳定文件名与内容。"""
name: str
content: bytes
@dataclass(frozen=True, slots=True)
class SystemOperationResult:
"""系统管理用例返回给传输层的稳定执行结果。"""
success: bool
message: str | None = None
data: Any = None
@dataclass(frozen=True, slots=True)
class MarketFetchResult:
"""Wiki 市场清单传输端口返回的状态与仓库列表。"""
status_code: int | None
repos: list[str]
class SystemLogPort(Protocol):
"""日志文件发现、读取与轮询的异步端口。"""
async def read(self, logfile: str) -> str:
"""读取一个受准入保护的日志文件。"""
...
async def follow(
self,
logfile: str,
length: int,
disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
"""返回历史尾部及后续新增日志行。"""
...
async def collect(self, name: str) -> list[LogFileData]:
"""读取一个主程序或插件日志归档集合。"""
...
class PluginMarketPort(Protocol):
"""读取并解析 Wiki 插件市场清单的传输端口。"""
async def fetch(self, url: str) -> MarketFetchResult:
"""读取指定 Wiki 文档并返回规范化仓库列表。"""
...
class ConfigurationEventPort(Protocol):
"""发布系统配置变更事实的端口。"""
async def publish(self, key: Any, value: JsonData = None) -> None:
"""发布一个已经持久化完成的配置变更。"""
...
class ServerInfoPort(Protocol):
"""MoviePilot Server 查询能力的最小端口。"""
async def user_global(self) -> dict[str, Any]:
"""返回当前用户的服务端权限投影。"""
...
async def usage(self) -> dict[str, Any]:
"""返回匿名安装版本统计。"""
...
class ReleaseCatalogPort(Protocol):
"""读取 GitHub Release 目录的传输端口。"""
async def list(self) -> list[dict[str, Any]] | None:
"""返回 Release 列表,读取失败时返回空值。"""
...
class RuntimeFeaturePort(Protocol):
"""查询本机可选运行能力的端口。"""
def snapshot(self) -> dict[str, bool]:
"""返回 Rust 加速等本机能力快照。"""
...
class SystemControlPort(Protocol):
"""主进程更新和重启控制端口。"""
def can_restart(self) -> bool:
"""返回当前部署环境是否支持受管重启。"""
...
def restart(self) -> tuple[bool, str]:
"""请求重启并返回兼容结果。"""
...
def upgrade_dev(self) -> tuple[bool, str]:
"""执行开发分支更新。"""
...
class SystemUpdatePort(Protocol):
"""后台 Release 更新状态机端口。"""
def status(self) -> SystemUpdateStatus:
"""读取当前后台更新状态。"""
...
def check(self) -> SystemUpdateStatus:
"""立即检查正式版本更新。"""
...
def download(self) -> SystemUpdateStatus:
"""启动后台下载并返回当前状态。"""
...
def prepare_install(self) -> tuple[bool, str]:
"""确认消费已校验更新包。"""
...
def cancel_install(self, message: str) -> None:
"""在重启失败时撤销安装请求。"""
...
class LlmCapabilityPort(Protocol):
"""校验 LLM 服务端工具能力的端口。"""
def validate(self, env: dict[str, Any], settings: RuntimeSettingsService) -> str | None:
"""校验本次设置变更是否请求了不可用能力。"""
...
class SystemService:
"""集中执行 System API 的日志、设置、市场和进程控制用例。"""
def __init__(
self,
*,
settings: RuntimeSettingsService,
system_config: SystemConfigService,
logs: SystemLogPort,
market: PluginMarketPort,
events: ConfigurationEventPort,
server: ServerInfoPort,
releases: ReleaseCatalogPort,
features: RuntimeFeaturePort,
control: SystemControlPort,
updates: SystemUpdatePort,
llm: LlmCapabilityPort,
plugin_mutation: Callable[[str], AbstractContextManager[None]],
rule_group_mutation: Callable[[], AbstractAsyncContextManager[AsyncRuleGroupMutationService]],
) -> None:
"""保存由启动组合根注入的全部外部端口。"""
self.settings = settings
self._system_config = system_config
self._logs = logs
self._market = market
self._events = events
self._server = server
self._releases = releases
self._features = features
self._control = control
self._updates = updates
self._llm = llm
self._plugin_mutation = plugin_mutation
self._rule_group_mutation = rule_group_mutation
async def read_log(self, logfile: str) -> str:
"""读取日志并按旧接口语义倒序返回。"""
text = await self._logs.read(logfile)
return "\n".join(text.split("\n")[::-1])
async def follow_log(
self,
logfile: str,
length: int,
disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
"""取得日志轮询数据源,传输层只负责 SSE framing。"""
return await self._logs.follow(logfile, length, disconnected)
async def collect_logs(self, name: str) -> list[LogFileData]:
"""读取日志归档条目,传输层只负责 ZIP framing。"""
return await self._logs.collect(name)
async def update_environment(self, env: dict[str, Any]) -> SystemOperationResult:
"""校验并原子执行一批可变部署设置更新。"""
validation_error = self._llm.validate(env, self.settings)
if validation_error:
return SystemOperationResult(False, validation_error)
validation_error = self._validate_database_backup_config(env)
if validation_error:
return SystemOperationResult(False, validation_error)
result = self.settings.update_many(env)
success_updates = {key: value for key, value in result.items() if value[0]}
failed_updates = {key: value for key, value in result.items() if value[0] is False}
if failed_updates:
return SystemOperationResult(
False,
", ".join(value[1] for value in failed_updates.values()),
{"success_updates": success_updates, "failed_updates": failed_updates},
)
if success_updates:
await self._events.publish(success_updates.keys())
return SystemOperationResult(
True,
"所有配置项更新成功",
{"success_updates": success_updates},
)
async def sync_plugin_market(self, wiki_url: str | None) -> SystemOperationResult:
"""读取 Wiki 清单、合并本地仓库并更新运行设置。"""
source_url = (wiki_url or PLUGIN_MARKET_WIKI_URL).strip()
if not self._is_allowed_wiki_url(source_url):
return SystemOperationResult(False, "不支持的 Wiki 同步地址")
fetched = await self._market.fetch(source_url)
if fetched.status_code is None:
return SystemOperationResult(False, "无法访问 Wiki 插件仓库清单")
if fetched.status_code != 200:
return SystemOperationResult(
False, f"访问 Wiki 插件仓库清单失败,状态码:{fetched.status_code}"
)
if not fetched.repos:
return SystemOperationResult(False, "未在 Wiki 中识别到插件仓库地址")
local_repos = self._split_repos(self.settings.get("PLUGIN_MARKET", ""))
local_keys = {repo.lower() for repo in local_repos}
added_count = sum(repo.lower() not in local_keys for repo in fetched.repos)
merged_repos = self._merge_repos(local_repos, fetched.repos)
merged_value = ",".join(merged_repos)
success, message = self.settings.update("PLUGIN_MARKET", merged_value)
if success:
await self._events.publish("PLUGIN_MARKET", merged_value)
elif success is None:
success = True
return SystemOperationResult(
bool(success),
message,
{
"value": merged_value,
"repos": merged_repos,
"wiki_repos": fetched.repos,
"added_count": added_count,
"total_count": len(merged_repos),
"source_url": source_url,
},
)
async def update_setting(self, key: str, value: JsonData) -> SystemOperationResult:
"""按配置所有权更新运行设置或持久化系统配置。"""
if self.settings.contains(key):
success, message = self.settings.update(key, value)
if success:
await self._events.publish(key, value)
elif success is None:
success = True
return SystemOperationResult(bool(success), message)
if key not in {item.value for item in SystemConfigKey}:
return SystemOperationResult(False, f"配置项 '{key}' 不存在")
if isinstance(value, list):
value = list(filter(None, value)) or None
try:
with self._plugin_mutation(key):
event_value: JsonData = value
if key == SystemConfigKey.UserFilterRuleGroups.value:
current = self._system_config.get(SystemConfigKey.UserFilterRuleGroups)
expected = self._dict_list(current)
definitions = self._dict_list(value)
async with self._rule_group_mutation() as mutation:
await mutation.apply(definitions, expected_rule_groups=expected)
event_value = definitions
success = True
else:
success = await self._system_config.async_set(key, value)
if success:
await self._events.publish(key, event_value)
return SystemOperationResult(True)
except PluginMutationRejectedError as error:
return SystemOperationResult(False, str(error))
async def user_global(self) -> dict[str, Any]:
"""返回 MoviePilot Server 用户权限投影。"""
return await self._server.user_global()
async def usage(self) -> dict[str, Any]:
"""返回安装版本统计。"""
return await self._server.usage()
async def releases(self) -> list[dict[str, Any]] | None:
"""返回 GitHub Release 目录。"""
return await self._releases.list()
def runtime_features(self) -> dict[str, bool]:
"""返回本机可选运行能力快照。"""
return self._features.snapshot()
def restart(self) -> SystemOperationResult:
"""执行受管重启。"""
if not self._control.can_restart():
return SystemOperationResult(False, "当前运行环境不支持重启操作!")
success, message = self._control.restart()
return SystemOperationResult(success, message)
def upgrade(self, mode: str | None) -> SystemOperationResult:
"""仅保留兼容的开发分支更新入口。"""
if str(mode or "").strip().lower() != "dev":
return SystemOperationResult(
False, "Release 更新请使用 /system/update/check、download 和 install 接口"
)
if not self._control.can_restart():
return SystemOperationResult(False, "当前运行环境不支持升级操作!")
success, message = self._control.upgrade_dev()
return SystemOperationResult(success, message)
def update_status(self) -> SystemUpdateStatus:
"""读取后台更新状态。"""
return self._updates.status()
def check_update(self) -> SystemUpdateStatus:
"""立即检查正式版本更新。"""
return self._updates.check()
def download_update(self) -> SystemOperationResult:
"""校验环境并启动后台更新下载。"""
if not self._control.can_restart():
return SystemOperationResult(False, "当前运行环境不支持升级操作!")
status = self._updates.download()
return SystemOperationResult(status.state != "failed", status.error, status)
def install_update(self) -> SystemOperationResult:
"""确认更新包并在重启失败时回滚安装请求。"""
if not self._control.can_restart():
return SystemOperationResult(False, "当前运行环境不支持升级操作!")
prepared, message = self._updates.prepare_install()
if not prepared:
return SystemOperationResult(False, message)
success, restart_message = self._control.restart()
if not success:
self._updates.cancel_install(restart_message)
return SystemOperationResult(False, restart_message)
return SystemOperationResult(True, message)
def _validate_database_backup_config(self, env: dict[str, Any]) -> str | None:
"""在批量写入前校验数据库备份策略。"""
if not _DATABASE_BACKUP_SETTING_KEYS.intersection(env):
return None
cron = str(env.get("DB_BACKUP_CRON", self.settings.get("DB_BACKUP_CRON")) or "").strip()
if cron:
try:
TimerUtils.normalize_schedule_trigger(
"cron", cron, self.settings.get("TZ")
)
except (TypeError, ValueError):
return "数据库备份周期格式不正确"
backup_path = env.get("DB_BACKUP_PATH", self.settings.get("DB_BACKUP_PATH"))
if backup_path is not None and not isinstance(backup_path, str):
return "数据库备份目录必须是路径字符串"
for key, label in (
("DB_BACKUP_RETENTION_DAYS", "数据库备份过期天数"),
("DB_BACKUP_MAX_COUNT", "数据库备份最大保留份数"),
):
value = env.get(key, self.settings.get(key))
if isinstance(value, bool):
return f"{label}必须是大于等于 0 的整数"
try:
converted = int(value)
except (TypeError, ValueError):
return f"{label}必须是大于等于 0 的整数"
if converted < 0 or str(value).strip() != str(converted):
return f"{label}必须是大于等于 0 的整数"
return None
@staticmethod
def _is_allowed_wiki_url(wiki_url: str) -> bool:
"""限制 Wiki 同步到维护者控制的固定文档源。"""
parsed = urlparse(wiki_url)
return (
parsed.scheme == "https"
and (parsed.hostname or "").lower() == "raw.githubusercontent.com"
and bool(re.fullmatch(r"/jxxghp/MoviePilot-Wiki/[^/]+/plugin\.md", parsed.path))
)
@staticmethod
def _split_repos(value: Any) -> list[str]:
"""拆分并规范化逗号分隔的仓库地址。"""
return SystemService._merge_repos([], str(value or "").split(","))
@staticmethod
def _merge_repos(existing: list[str], incoming: list[str]) -> list[str]:
"""按来源顺序合并仓库地址并执行大小写不敏感去重。"""
merged: list[str] = []
seen: set[str] = set()
for repo in (*existing, *incoming):
normalized = str(repo or "").strip().rstrip("/")
key = normalized.lower()
if normalized and key not in seen:
seen.add(key)
merged.append(normalized)
return merged
@staticmethod
def _dict_list(value: JsonData) -> list[dict[str, Any]]:
"""只保留规则组列表中的字典定义并复制输入。"""
if not isinstance(value, list):
return []
return [dict(item) for item in value if isinstance(item, dict)]

View File

@@ -33,6 +33,7 @@ from app.application.subscription.write import (
from app.application.subscription.write import (
AsyncUnitOfWork as SubscriptionAsyncUnitOfWork,
)
from app.application.system import SystemService
from app.application.transfer.execution import TransferExecutionRepository
from app.application.workflow import WorkflowCachePort, WorkflowQueryService
from app.runtime.tasks import TaskRegistry
@@ -244,6 +245,7 @@ class HostRuntime:
site: SiteRuntime
subscription: SubscriptionRuntime
workflow: WorkflowRuntime
system: SystemService
configuration: RuntimeConfiguration
settings: RuntimeSettingsService
tasks: TaskRegistry

View File

@@ -160,6 +160,7 @@ def compose_runtime(inputs: RuntimeInputs) -> RuntimeComposition:
rule_group_mutation_scope,
site_reference_mutation_scope,
)
from app.startup.composition.system import compose_system_service
dependencies = inputs.dependencies
configuration = inputs.configuration
@@ -170,6 +171,10 @@ def compose_runtime(inputs: RuntimeInputs) -> RuntimeComposition:
system_config=inputs.authentication.system_config,
passkey=inputs.authentication.passkey,
)
async_rule_scope = partial(
async_rule_group_mutation_scope,
configuration.system_config.publish_many,
)
host_runtime = HostRuntime(
agent_chat=AgentChatRuntime(
async_session=get_async_db,
@@ -213,10 +218,7 @@ def compose_runtime(inputs: RuntimeInputs) -> RuntimeComposition:
rule_group_mutation_scope,
configuration.system_config.publish_many,
),
async_rule_group_mutation_scope=partial(
async_rule_group_mutation_scope,
configuration.system_config.publish_many,
),
async_rule_group_mutation_scope=async_rule_scope,
site_reference_mutation_scope=partial(
site_reference_mutation_scope,
configuration.system_config.publish_many,
@@ -227,6 +229,11 @@ def compose_runtime(inputs: RuntimeInputs) -> RuntimeComposition:
repository=cast(RepositoryFactory, WorkflowOper),
system_config=lambda: configuration.system_service,
),
system=compose_system_service(
settings=configuration.settings,
system_config=configuration.system_service,
rule_group_mutation=async_rule_scope,
),
configuration=configuration.runtime,
settings=configuration.settings,
tasks=inputs.tasks,

View File

@@ -0,0 +1,326 @@
"""System API 外部能力的唯一启动组合根。"""
from __future__ import annotations
import asyncio
import re
from collections import deque
from collections.abc import AsyncIterator, Awaitable, Callable
from pathlib import Path
from typing import Any, cast
import aiofiles # type: ignore[import-untyped]
from anyio import Path as AsyncPath
from app.adapters.external.plugin.client import extract_plugin_market_repos_from_wiki
from app.adapters.external.server import MoviePilotServerHelper
from app.adapters.network.http import AsyncRequestUtils
from app.adapters.system import rust as rust_accel
from app.adapters.system.update import system_update_manager
from app.application.configuration import RuntimeSettingsService, SystemConfigService
from app.application.plugin.runtime import plugin_system_config_mutation
from app.application.security.url import SecurityUtils
from app.application.system import (
ConfigurationEventPort,
LlmCapabilityPort,
LogFileData,
LogNotFoundError,
MarketFetchResult,
PluginMarketPort,
ReleaseCatalogPort,
RuntimeFeaturePort,
ServerInfoPort,
SystemControlPort,
SystemLogPort,
SystemService,
SystemUpdatePort,
)
from app.runtime.events import eventmanager
from app.runtime.state import SystemHelper
from app.runtime.stop import runtime_stop_state
from app.schemas.event import ConfigChangeEventData
from app.schemas.system import SystemUpdateStatus
from app.schemas.types import EventType
_LOG_DOWNLOAD_LIMIT = 10
_LOG_DOWNLOAD_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
class _FileLogAdapter(SystemLogPort):
"""以受限日志根实现文件读取、尾随和归档数据源。"""
def __init__(self, settings: RuntimeSettingsService) -> None:
"""保存日志根设置提供器。"""
self._settings = settings
async def read(self, logfile: str) -> str:
"""校验路径后异步读取完整日志文本。"""
path = await self._resolve_logfile(logfile)
async with aiofiles.open(path, mode="r", encoding="utf-8", errors="replace") as file:
return cast(str, await file.read())
async def follow(
self,
logfile: str,
length: int,
disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
"""先返回历史尾部,再轮询并返回新增日志行。"""
path = await self._resolve_logfile(logfile)
return self._follow_path(path, length, disconnected)
async def collect(self, name: str) -> list[LogFileData]:
"""在线程中发现并读取允许归档的日志文件。"""
return await asyncio.to_thread(self._collect_sync, name)
async def _resolve_logfile(self, logfile: str) -> Path:
"""把相对日志名解析为日志根内的现存 .log 文件。"""
root = Path(self._settings.get("LOG_PATH"))
path = root / str(logfile or "")
safe = await SecurityUtils.async_is_safe_path(
base_path=AsyncPath(root),
user_path=AsyncPath(path),
allowed_suffixes={".log"},
)
if not safe or not await asyncio.to_thread(path.is_file):
raise LogNotFoundError(logfile)
return path
async def _follow_path(
self,
path: Path,
length: int,
disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
"""对一个已准入文件执行有界历史读取和新增内容轮询。"""
lines_queue: deque[str] = deque(maxlen=max(length, 50))
file_size = (await asyncio.to_thread(path.stat)).st_size
async with aiofiles.open(path, mode="r", encoding="utf-8", errors="replace") as file:
if file_size > 100 * 1024:
position = file_size - min(file_size, 100 * 1024)
await file.seek(position)
content = await file.read()
first_newline = content.find("\n")
if first_newline != -1:
content = content[first_newline + 1 :]
else:
content = await file.read()
for line in (item.strip() for item in content.splitlines() if item.strip()):
lines_queue.append(line)
for line in lines_queue:
yield line
async with aiofiles.open(path, mode="r", encoding="utf-8", errors="replace") as file:
await file.seek(0, 2)
previous_size = (await asyncio.to_thread(path.stat)).st_size
while not runtime_stop_state.is_system_stopped:
if await disconnected():
break
current_size = (await asyncio.to_thread(path.stat)).st_size
if current_size > previous_size:
line = (await file.readline()).strip()
if line:
yield line
previous_size = current_size
else:
await asyncio.sleep(0.5)
def _collect_sync(self, name: str) -> list[LogFileData]:
"""同步发现并读取最多十个主程序或指定插件日志。"""
normalized = str(name or "").strip().lower()
if not normalized or not _LOG_DOWNLOAD_NAME_PATTERN.fullmatch(normalized):
raise LogNotFoundError(name)
root = Path(self._settings.get("LOG_PATH"))
directory = root if normalized == "moviepilot" else root / "plugins"
prefix = "moviepilot.log" if normalized == "moviepilot" else f"{normalized}.log"
if not directory.is_dir():
raise LogNotFoundError(name)
current = directory / prefix
backups = [
item
for item in directory.iterdir()
if item.is_file() and item.name.startswith(f"{prefix}.")
]
backups.sort(key=lambda item: item.stat().st_mtime, reverse=True)
paths = ([current] if current.is_file() else []) + backups
entries: list[LogFileData] = []
for path in paths[:_LOG_DOWNLOAD_LIMIT]:
if not SecurityUtils.is_safe_path(base_path=root, user_path=path):
raise LogNotFoundError(name)
entries.append(LogFileData(name=path.name, content=path.read_bytes()))
if not entries:
raise LogNotFoundError(name)
return entries
class _PluginMarketAdapter(PluginMarketPort):
"""通过统一异步 HTTP 客户端读取并解析 Wiki 市场清单。"""
def __init__(self, settings: RuntimeSettingsService) -> None:
"""保存代理与 User-Agent 设置提供器。"""
self._settings = settings
async def fetch(self, url: str) -> MarketFetchResult:
"""读取 Wiki 文本并把解析异常收敛为空仓库列表。"""
response = await AsyncRequestUtils(
ua=self._settings.get("USER_AGENT"),
proxies=self._settings.get("PROXY"),
timeout=30,
accept_type="text/plain,*/*",
).get_res(url)
if response is None:
return MarketFetchResult(status_code=None, repos=[])
repos = (
extract_plugin_market_repos_from_wiki(response.text)
if response.status_code == 200
else []
)
return MarketFetchResult(status_code=response.status_code, repos=repos)
class _ConfigurationEventAdapter(ConfigurationEventPort):
"""把已提交设置变更发布到宿主事件总线。"""
async def publish(self, key: Any, value: Any = None) -> None:
"""发布兼容 ConfigChanged 事件。"""
await eventmanager.async_send_event(
etype=EventType.ConfigChanged,
data=ConfigChangeEventData(key=key, value=value, change_type="update"),
)
class _ServerInfoAdapter(ServerInfoPort):
"""适配 MoviePilot Server 的用户权限与统计接口。"""
async def user_global(self) -> dict[str, Any]:
"""合并用户 UUID 与两项共享管理权限。"""
is_admin = await MoviePilotServerHelper.async_is_admin_user()
return {
"USER_UNIQUE_ID": MoviePilotServerHelper.get_user_uuid(),
"SUBSCRIBE_SHARE_MANAGE": is_admin,
"WORKFLOW_SHARE_MANAGE": is_admin,
}
async def usage(self) -> dict[str, Any]:
"""读取安装版本统计。"""
return await MoviePilotServerHelper.async_get_usage_statistic()
class _ReleaseCatalogAdapter(ReleaseCatalogPort):
"""通过 GitHub API 读取主程序 Release 列表。"""
def __init__(self, settings: RuntimeSettingsService) -> None:
"""保存 GitHub 代理与请求头设置提供器。"""
self._settings = settings
async def list(self) -> list[dict[str, Any]] | None:
"""读取有效 JSON 列表,失败时返回空值。"""
response = await AsyncRequestUtils(
proxies=self._settings.get("PROXY"),
headers=self._settings.get("GITHUB_HEADERS"),
).get_res("https://api.github.com/repos/jxxghp/MoviePilot/releases")
if response is None or response.status_code != 200:
return None
payload = response.json()
return payload if isinstance(payload, list) else None
class _RuntimeFeatureAdapter(RuntimeFeaturePort):
"""适配本机 Rust 加速能力探测。"""
def snapshot(self) -> dict[str, bool]:
"""返回现有环境接口使用的四项 Rust 状态。"""
return {
"RUST_ACCEL": rust_accel.is_config_enabled(),
"RUST_ACCEL_AVAILABLE": rust_accel.is_available(),
"RUST_ACCEL_ENABLED": rust_accel.is_enabled(),
"RUST_ACCEL_REQUIRED": rust_accel.is_required(),
}
class _SystemControlAdapter(SystemControlPort):
"""适配宿主进程的重启与开发分支更新控制。"""
def can_restart(self) -> bool:
"""查询部署环境重启能力。"""
return SystemHelper.can_restart()
def restart(self) -> tuple[bool, str]:
"""请求宿主重启。"""
return SystemHelper.restart()
def upgrade_dev(self) -> tuple[bool, str]:
"""执行开发分支更新。"""
return SystemHelper.upgrade_dev()
class _SystemUpdateAdapter(SystemUpdatePort):
"""适配后台 Release 更新状态机。"""
def status(self) -> SystemUpdateStatus:
"""读取当前更新状态。"""
return system_update_manager.get_status()
def check(self) -> SystemUpdateStatus:
"""立即检查更新。"""
return system_update_manager.check()
def download(self) -> SystemUpdateStatus:
"""启动后台下载。"""
return system_update_manager.start_download()
def prepare_install(self) -> tuple[bool, str]:
"""确认安装准备。"""
return system_update_manager.request_install()
def cancel_install(self, message: str) -> None:
"""撤销失败的安装请求。"""
system_update_manager.cancel_install(message)
class _LlmCapabilityAdapter(LlmCapabilityPort):
"""适配 Agent 目录中的服务端工具能力注册表。"""
def validate(self, env: dict[str, Any], settings: RuntimeSettingsService) -> str | None:
"""拒绝所选模型不支持的强制内建联网搜索。"""
from app.agent.llm.tools import ServerToolRegistry, ServerToolUnavailableError
mode = ServerToolRegistry.normalize_web_search_mode(
env.get("LLM_WEB_SEARCH_MODE", settings.get("LLM_WEB_SEARCH_MODE", "local"))
)
if mode != "builtin":
return None
provider = str(env.get("LLM_PROVIDER", settings.get("LLM_PROVIDER", "")) or "").strip()
model = str(env.get("LLM_MODEL", settings.get("LLM_MODEL", "")) or "").strip()
base_url = env.get("LLM_BASE_URL", settings.get("LLM_BASE_URL"))
if ServerToolRegistry.get_capability(
provider=provider,
model=model,
base_url=str(base_url or "").strip() or None,
tool_id="web_search",
):
return None
return str(ServerToolUnavailableError(provider=provider, model=model, tool_id="web_search"))
def compose_system_service(
*,
settings: RuntimeSettingsService,
system_config: SystemConfigService,
rule_group_mutation: Callable[[], Any],
) -> SystemService:
"""构造 System API 应用服务并注入全部具体外部能力。"""
return SystemService(
settings=settings,
system_config=system_config,
logs=_FileLogAdapter(settings),
market=_PluginMarketAdapter(settings),
events=_ConfigurationEventAdapter(),
server=_ServerInfoAdapter(),
releases=_ReleaseCatalogAdapter(settings),
features=_RuntimeFeatureAdapter(),
control=_SystemControlAdapter(),
updates=_SystemUpdateAdapter(),
llm=_LlmCapabilityAdapter(),
plugin_mutation=plugin_system_config_mutation,
rule_group_mutation=rule_group_mutation,
)

View File

@@ -833,6 +833,14 @@ expired claimed task remains exclusively owned by fenced recovery APIs.
only authenticates, maps request fields and projects the standard response;
startup injects the concrete HTTP transport with certificate verification and
automatic redirects disabled.
- System management use cases live in `app/application/system.py`: log discovery,
reading and polling, Wiki market synchronization and merge, runtime/system
setting mutation, configuration events, release queries, and update/restart
orchestration all depend on explicit Ports. `app/startup/composition/system.py`
injects the concrete HTTP, filesystem, MoviePilot Server, Rust and process-update
adapters into `HostRuntime.system`. The System endpoint retains authentication,
HTTP error/DTO projection, SSE framing and ZIP framing only; it must not import
those concrete adapters or the event bus directly.
- `app/runtime/compat` stores string mappings and resolves aliases lazily. It may
not eagerly import canonical MoviePilot modules.
- 已删除的 `app.db.<entity>_oper` 路径继续由精确模块映射提供给旧插件;其中订阅写入、

View File

@@ -963,16 +963,12 @@
"type-arg": 2
},
"app/api/endpoints/system.py": {
"arg-type": 2,
"arg-type": 1,
"attr-defined": 4,
"import-untyped": 1,
"misc": 34,
"no-untyped-call": 7,
"no-untyped-def": 27,
"operator": 1,
"type-arg": 11,
"type-var": 2,
"var-annotated": 1
"type-arg": 9
},
"app/api/endpoints/tmdb.py": {
"attr-defined": 1,

View File

@@ -2621,7 +2621,65 @@ def test_cache_initializer_delegates_construction_to_composition():
]
assert calls == ["configure_cache_composition"]
def test_system_api_business_orchestration_is_owned_by_application_service():
"""System API 只保留传输映射,不得重新拥有日志、设置或更新实现。"""
endpoint_path = APP_ROOT / "api" / "endpoints" / "system.py"
endpoint_tree = ast.parse(
endpoint_path.read_text(encoding="utf-8-sig"),
filename=str(endpoint_path),
)
imported = {
node.module
for node in ast.walk(endpoint_tree)
if isinstance(node, ast.ImportFrom) and node.module
}
direct_adapters = {
module
for module in imported
if module.startswith("app.adapters")
and module != "app.adapters.web.security.access"
}
endpoint_functions = {
node.name
for node in endpoint_tree.body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
}
retired_helpers = {
"_collect_named_log_files",
"_validate_database_backup_config",
"_validate_llm_server_tool_config",
"_is_allowed_plugin_market_wiki_url",
}
assert not direct_adapters
assert endpoint_functions.isdisjoint(retired_helpers)
assert not imported.intersection(
{
"app.application.plugin.runtime",
"app.runtime.events",
"app.runtime.state",
}
)
application_path = APP_ROOT / "application" / "system.py"
application_tree = ast.parse(
application_path.read_text(encoding="utf-8-sig"),
filename=str(application_path),
)
assert not any(
isinstance(node, ast.ImportFrom)
and node.module
and node.module.startswith("app.adapters")
for node in ast.walk(application_tree)
)
composition_source = (
APP_ROOT / "startup" / "composition" / "system.py"
).read_text(encoding="utf-8-sig")
assert "def compose_system_service(" in composition_source
assert "system=compose_system_service(" in (
APP_ROOT / "startup" / "composition" / "runtime.py"
).read_text(encoding="utf-8-sig")
PROCESS_LEVEL_ROOTS = (
"app.api",
"app.chain",

View File

@@ -204,6 +204,7 @@ def _runtime() -> HostRuntime:
repository=_Repository,
system_config=lambda: _Repository(object()),
),
system=SimpleNamespace(),
configuration=RuntimeConfiguration(
api=lambda: ApiRuntimeConfig(60, False, True),
scheduler=lambda: SchedulerRuntimeConfig(

View File

@@ -1,15 +1,22 @@
import asyncio
import signal
import threading
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi import FastAPI
from app.adapters.network import http as http_utils
from app.application.configuration import (
get_configured_system_config,
get_runtime_settings,
)
from app.runtime.config import settings as runtime_settings
from app.runtime.tasks import configure_task_registry, get_task_registry
from app.startup import lifecycle
from app.startup.composition.system import compose_system_service
from app.startup.initializers import modules as modules_initializer
@@ -28,6 +35,23 @@ def _assert_completed_once(mock: MagicMock) -> None:
mock.assert_called_once()
def _system_runtime():
"""构造使用真实系统控制适配器的最小运行时。"""
@asynccontextmanager
async def rule_group_mutation():
"""提供本组测试不会进入的规则组事务替身。"""
yield SimpleNamespace()
return SimpleNamespace(
system=compose_system_service(
settings=get_runtime_settings(),
system_config=get_configured_system_config(),
rule_group_mutation=rule_group_mutation,
)
)
def _patch_lifespan(monkeypatch, *, failing_step: str | None = None) -> dict:
"""隔离 lifespan 的外部依赖,并按名称注入一个关闭失败"""
monkeypatch.setattr(runtime_settings, "MOVIEPILOT_SAFE_MODE", False)
@@ -1093,20 +1117,29 @@ def test_restart_endpoint_failure_preserves_stop_state(
if initially_stopped:
stop_event.set()
monkeypatch.setattr(system.runtime_stop_state, "_system_event", stop_event)
monkeypatch.setattr(system.SystemHelper, "can_restart", MagicMock(return_value=True))
monkeypatch.setattr(system.SystemHelper, "restart", MagicMock(return_value=(False, "restart failed")))
monkeypatch.setattr(
system.system_update_manager,
"request_install",
"app.startup.composition.system.SystemHelper.can_restart",
MagicMock(return_value=True),
)
monkeypatch.setattr(
"app.startup.composition.system.SystemHelper.restart",
MagicMock(return_value=(False, "restart failed")),
)
monkeypatch.setattr(
"app.startup.composition.system.system_update_manager.request_install",
MagicMock(return_value=(True, "prepared")),
)
cancel_install = MagicMock()
monkeypatch.setattr(system.system_update_manager, "cancel_install", cancel_install)
monkeypatch.setattr(
"app.startup.composition.system.system_update_manager.cancel_install",
cancel_install,
)
runtime = _system_runtime()
if endpoint_name == "restart_system":
response = system.restart_system(None)
response = system.restart_system(None, runtime)
else:
response = system.install_system_update(None)
response = system.install_system_update(None, runtime)
assert not response.success
assert stop_event.is_set() is initially_stopped
@@ -1120,13 +1153,19 @@ def test_upgrade_endpoint_retains_dev_mode_only(monkeypatch):
"""旧升级入口只保留 Dev,Release 必须迁移到后台下载流程。"""
from app.api.endpoints import system
monkeypatch.setattr(system.SystemHelper, "can_restart", MagicMock(return_value=True))
monkeypatch.setattr(
"app.startup.composition.system.SystemHelper.can_restart",
MagicMock(return_value=True),
)
upgrade_dev = MagicMock(return_value=(True, "dev queued"))
monkeypatch.setattr(system.SystemHelper, "upgrade_dev", upgrade_dev)
monkeypatch.setattr(
"app.startup.composition.system.SystemHelper.upgrade_dev", upgrade_dev
)
runtime = _system_runtime()
dev_response = system.upgrade_system("dev", None)
release_response = system.upgrade_system("release", None)
legacy_default_response = system.upgrade_system(None, None)
dev_response = system.upgrade_system("dev", None, runtime)
release_response = system.upgrade_system("release", None, runtime)
legacy_default_response = system.upgrade_system(None, None, runtime)
assert dev_response.success
assert not release_response.success

View File

@@ -1,6 +1,7 @@
import asyncio
from contextlib import nullcontext
from contextlib import asynccontextmanager, nullcontext
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -834,15 +835,32 @@ def test_sync_plugin_market_from_wiki_merges_and_deduplicates_repos():
runtime_settings = MagicMock()
runtime_settings.get.return_value = "https://github.com/local/existing"
runtime_settings.update.return_value = (True, "")
@asynccontextmanager
async def rule_group_mutation():
"""提供本用例不会进入的规则组事务替身。"""
yield SimpleNamespace()
from app.startup.composition.system import compose_system_service
runtime = SimpleNamespace(
system=compose_system_service(
settings=runtime_settings,
system_config=MagicMock(),
rule_group_mutation=rule_group_mutation,
)
)
with (
patch("app.api.endpoints.system.AsyncRequestUtils", return_value=request_utils),
patch(
"app.api.endpoints.system.get_runtime_settings",
return_value=runtime_settings,
"app.startup.composition.system.AsyncRequestUtils",
return_value=request_utils,
),
patch("app.api.endpoints.system.eventmanager.async_send_event", new=AsyncMock()) as send_event,
patch(
"app.startup.composition.system.eventmanager.async_send_event",
new=AsyncMock(),
) as send_event,
):
result = asyncio.run(sync_plugin_market_from_wiki(None, None))
result = asyncio.run(sync_plugin_market_from_wiki(None, None, runtime))
assert result.success
assert result.data["repos"] == [

View File

@@ -13,6 +13,7 @@ from app.api.endpoints import system as system_endpoint
from app.application.plugin import runtime as plugin_runtime
from app.runtime.extensions.plugin.admission import PluginMutationAdmission
from app.schemas.types import SystemConfigKey
from app.startup.composition.system import compose_system_service
PLUGIN_RUNTIME_KEYS = (
SystemConfigKey.UserInstalledPlugins,
@@ -21,6 +22,17 @@ PLUGIN_RUNTIME_KEYS = (
)
def _runtime(config, *, rule_group_mutation=None):
"""构造注入指定配置仓储的最小系统运行时。"""
return SimpleNamespace(
system=compose_system_service(
settings=SimpleNamespace(contains=lambda _key: False),
system_config=config,
rule_group_mutation=rule_group_mutation or SimpleNamespace(),
)
)
@pytest.mark.asyncio
@pytest.mark.parametrize("config_key", PLUGIN_RUNTIME_KEYS)
async def test_system_http_rejects_plugin_keys_after_admission_seal(
@@ -37,18 +49,9 @@ async def test_system_http_rejects_plugin_keys_after_admission_seal(
"get_plugin_manager",
lambda: SimpleNamespace(mutation=admission.hold),
)
monkeypatch.setattr(
system_endpoint,
"get_runtime_settings",
lambda: SimpleNamespace(contains=lambda _key: False),
response = await system_endpoint.set_setting(
config_key.value, {}, None, runtime=_runtime(config)
)
monkeypatch.setattr(
system_endpoint,
"get_configured_system_config",
lambda: config,
)
response = await system_endpoint.set_setting(config_key.value, {}, None)
assert response.success is False
assert "停机阶段" in response.message
@@ -108,22 +111,15 @@ async def test_system_http_plugin_write_remains_owned_until_settled(
lambda: SimpleNamespace(mutation=admission.hold),
)
monkeypatch.setattr(
system_endpoint,
"get_runtime_settings",
lambda: SimpleNamespace(contains=lambda _key: False),
"app.startup.composition.system.eventmanager.async_send_event", AsyncMock()
)
monkeypatch.setattr(
system_endpoint,
"get_configured_system_config",
lambda: config,
)
monkeypatch.setattr(system_endpoint.eventmanager, "async_send_event", AsyncMock())
task = asyncio.create_task(
system_endpoint.set_setting(
SystemConfigKey.UserInstalledPlugins.value,
["DemoPlugin"],
None,
runtime=_runtime(config),
)
)
await write_started.wait()
@@ -206,21 +202,14 @@ async def test_non_plugin_system_config_does_not_resolve_plugin_runtime(
monkeypatch.setattr(plugin_runtime, "get_plugin_manager", fail_runtime_resolution)
monkeypatch.setattr(
system_endpoint,
"get_runtime_settings",
lambda: SimpleNamespace(contains=lambda _key: False),
"app.startup.composition.system.eventmanager.async_send_event", AsyncMock()
)
monkeypatch.setattr(
system_endpoint,
"get_configured_system_config",
lambda: config,
)
monkeypatch.setattr(system_endpoint.eventmanager, "async_send_event", AsyncMock())
response = await system_endpoint.set_setting(
SystemConfigKey.Directories.value,
[],
None,
runtime=_runtime(config),
)
assert response.success is True
@@ -244,22 +233,11 @@ async def test_rule_group_setting_reconciles_stale_references_when_unchanged(
"""提供可观测的异步规则组事务作用域。"""
yield mutation
runtime = SimpleNamespace(
subscription=SimpleNamespace(
async_rule_group_mutation_scope=mutation_scope,
)
)
send_event = AsyncMock()
monkeypatch.setattr(
system_endpoint,
"get_runtime_settings",
lambda: SimpleNamespace(contains=lambda _key: False),
"app.startup.composition.system.eventmanager.async_send_event", send_event
)
monkeypatch.setattr(
system_endpoint,
"get_configured_system_config",
lambda: config,
)
monkeypatch.setattr(system_endpoint.eventmanager, "async_send_event", AsyncMock())
runtime = _runtime(config, rule_group_mutation=mutation_scope)
response = await system_endpoint.set_setting(
SystemConfigKey.UserFilterRuleGroups.value,
@@ -274,7 +252,7 @@ async def test_rule_group_setting_reconciles_stale_references_when_unchanged(
expected_rule_groups=definitions,
)
config.async_set.assert_not_awaited()
system_endpoint.eventmanager.async_send_event.assert_awaited_once()
send_event.assert_awaited_once()
@pytest.mark.asyncio

View File

@@ -1,12 +1,36 @@
"""系统数据库备份策略配置测试。"""
import asyncio
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from app.api.endpoints import system as system_endpoint
from app.application.configuration import (
get_configured_system_config,
get_runtime_settings,
)
from app.runtime.config import settings
from app.startup.composition.system import compose_system_service
def _runtime():
"""构造使用真实配置校验逻辑的最小系统运行时。"""
@asynccontextmanager
async def rule_group_mutation():
"""提供本组测试不会进入的规则组事务替身。"""
yield SimpleNamespace()
return SimpleNamespace(
system=compose_system_service(
settings=get_runtime_settings(),
system_config=get_configured_system_config(),
rule_group_mutation=rule_group_mutation,
)
)
@pytest.mark.parametrize(
@@ -26,7 +50,7 @@ def test_database_backup_policy_rejects_invalid_values(
) -> None:
"""无效策略必须在批量配置写入前被拒绝。"""
env["DB_BACKUP_ENABLE"] = True
assert message in str(system_endpoint._validate_database_backup_config(env))
assert message in str(_runtime().system._validate_database_backup_config(env))
@pytest.mark.parametrize(
@@ -46,13 +70,13 @@ def test_database_backup_policy_rejects_invalid_values(
def test_database_backup_policy_accepts_supported_boundaries(env: dict) -> None:
"""空目录使用默认路径,两个保留值的零均表示不限制。"""
env["DB_BACKUP_ENABLE"] = True
assert system_endpoint._validate_database_backup_config(env) is None
assert _runtime().system._validate_database_backup_config(env) is None
@pytest.mark.parametrize("disabled", [False, "false", "0", "off"])
def test_database_backup_policy_rejects_invalid_hidden_values_when_disabled(disabled) -> None:
"""关闭总开关只暂停调度,不能把无效策略写入持久配置。"""
error = system_endpoint._validate_database_backup_config({
error = _runtime().system._validate_database_backup_config({
"DB_BACKUP_ENABLE": disabled,
"DB_BACKUP_CRON": "invalid",
"DB_BACKUP_PATH": 123,
@@ -72,12 +96,10 @@ def test_set_env_rejects_invalid_database_backup_policy_without_partial_write()
"DB_BACKUP_MAX_COUNT": 30,
}
with patch.object(
system_endpoint,
"_validate_llm_server_tool_config",
return_value=None,
), patch.object(type(settings), "update_settings") as update_settings:
response = asyncio.run(system_endpoint.set_env_setting(env=env, _=object()))
with patch.object(type(settings), "update_settings") as update_settings:
response = asyncio.run(
system_endpoint.set_env_setting(env=env, _=object(), runtime=_runtime())
)
assert response.success is False
assert "数据库备份周期格式不正确" in response.message

View File

@@ -1,10 +1,34 @@
"""系统 LLM 服务端联网搜索配置测试。"""
import asyncio
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import patch
from app.api.endpoints import system as system_endpoint
from app.application.configuration import (
get_configured_system_config,
get_runtime_settings,
)
from app.runtime.config import settings
from app.startup.composition.system import compose_system_service
def _runtime():
"""构造使用真实 LLM 能力适配器的最小系统运行时。"""
@asynccontextmanager
async def rule_group_mutation():
"""提供本组测试不会进入的规则组事务替身。"""
yield SimpleNamespace()
return SimpleNamespace(
system=compose_system_service(
settings=get_runtime_settings(),
system_config=get_configured_system_config(),
rule_group_mutation=rule_group_mutation,
)
)
def test_set_env_rejects_unsupported_builtin_web_search() -> None:
@@ -17,7 +41,9 @@ def test_set_env_rejects_unsupported_builtin_web_search() -> None:
}
with patch.object(type(settings), "update_settings") as update_settings:
response = asyncio.run(system_endpoint.set_env_setting(env=env, _=object()))
response = asyncio.run(
system_endpoint.set_env_setting(env=env, _=object(), runtime=_runtime())
)
assert response.success is False
assert "不支持服务端联网搜索" in response.message
@@ -37,11 +63,12 @@ def test_set_env_accepts_supported_deepseek_builtin_web_search() -> None:
type(settings),
"update_settings",
return_value={key: (True, None) for key in env},
) as update_settings, patch.object(
system_endpoint.eventmanager,
"async_send_event",
) as update_settings, patch(
"app.startup.composition.system.eventmanager.async_send_event"
):
response = asyncio.run(system_endpoint.set_env_setting(env=env, _=object()))
response = asyncio.run(
system_endpoint.set_env_setting(env=env, _=object(), runtime=_runtime())
)
assert response.success is True
update_settings.assert_called_once_with(env=env)

View File

@@ -4,6 +4,7 @@ import asyncio
import io
import threading
import zipfile
from contextlib import asynccontextmanager
from pathlib import Path
from types import SimpleNamespace
@@ -12,7 +13,12 @@ from fastapi import HTTPException
from starlette.responses import Response
from app.api.endpoints import system as system_endpoint
from app.application.configuration import (
get_configured_system_config,
get_runtime_settings,
)
from app.runtime.config import settings
from app.startup.composition.system import compose_system_service
def test_logging_routes_use_superuser_dependency():
@@ -46,7 +52,34 @@ def fixture_isolated_log_path(monkeypatch, tmp_path: Path) -> Path:
return log_path
def test_logging_requires_superuser_dependency(monkeypatch, isolated_log_path):
@pytest.fixture(name="system_runtime")
def fixture_system_runtime(isolated_log_path):
"""构造使用真实文件日志 Adapter 的最小 HostRuntime 投影。"""
@asynccontextmanager
async def rule_group_mutation():
"""提供本组日志测试不会进入的规则组事务替身。"""
yield SimpleNamespace()
configured_settings = get_runtime_settings()
settings_port = SimpleNamespace(
get=lambda key, default=None: (
isolated_log_path
if key == "LOG_PATH"
else configured_settings.get(key, default)
)
)
service = compose_system_service(
settings=settings_port,
system_config=get_configured_system_config(),
rule_group_mutation=rule_group_mutation,
)
return SimpleNamespace(system=service)
def test_logging_requires_superuser_dependency(
monkeypatch, isolated_log_path, system_runtime
):
"""实时日志查看接口必须通过管理员依赖,普通资源令牌不能直接读取日志。"""
(isolated_log_path / "moviepilot.log").write_text("hello\n", encoding="utf-8")
response = asyncio.run(
@@ -55,13 +88,16 @@ def test_logging_requires_superuser_dependency(monkeypatch, isolated_log_path):
length=-1,
logfile="moviepilot.log",
_=SimpleNamespace(id=1, name="admin", is_superuser=True),
runtime=system_runtime,
)
)
assert isinstance(response, Response)
def test_download_moviepilot_logs_packages_latest_ten_log_files(isolated_log_path):
def test_download_moviepilot_logs_packages_latest_ten_log_files(
isolated_log_path, system_runtime
):
"""传入 moviepilot 时下载主程序滚动日志,最多打包 10 个文件。"""
for index in range(12):
(isolated_log_path / f"moviepilot.log.{index}").write_text(f"old-{index}", encoding="utf-8")
@@ -70,7 +106,11 @@ def test_download_moviepilot_logs_packages_latest_ten_log_files(isolated_log_pat
(isolated_log_path / "plugins").mkdir()
(isolated_log_path / "plugins" / "demo.log").write_text("plugin", encoding="utf-8")
response = asyncio.run(system_endpoint.download_logging(name="moviepilot", _=SimpleNamespace()))
response = asyncio.run(
system_endpoint.download_logging(
name="moviepilot", _=SimpleNamespace(), runtime=system_runtime
)
)
body = asyncio.run(_read_streaming_body(response))
with zipfile.ZipFile(io.BytesIO(body)) as archive:
@@ -87,7 +127,9 @@ def test_download_moviepilot_logs_packages_latest_ten_log_files(isolated_log_pat
assert "moviepilot.txt" not in names
def test_download_plugin_logs_packages_plugin_files_only(isolated_log_path):
def test_download_plugin_logs_packages_plugin_files_only(
isolated_log_path, system_runtime
):
"""传入插件 ID 时只下载该插件滚动日志,最多打包 10 个文件。"""
plugin_dir = isolated_log_path / "plugins"
plugin_dir.mkdir()
@@ -97,7 +139,11 @@ def test_download_plugin_logs_packages_plugin_files_only(isolated_log_path):
(plugin_dir / "other.log").write_text("other", encoding="utf-8")
(isolated_log_path / "moviepilot.log").write_text("main", encoding="utf-8")
response = asyncio.run(system_endpoint.download_logging(name="DemoPlugin", _=SimpleNamespace()))
response = asyncio.run(
system_endpoint.download_logging(
name="DemoPlugin", _=SimpleNamespace(), runtime=system_runtime
)
)
body = asyncio.run(_read_streaming_body(response))
with zipfile.ZipFile(io.BytesIO(body)) as archive:
@@ -112,27 +158,27 @@ def test_download_plugin_logs_packages_plugin_files_only(isolated_log_path):
assert "moviepilot.log" not in names
def test_download_log_zip_generation_runs_outside_event_loop_thread(monkeypatch, isolated_log_path):
def test_download_log_zip_generation_runs_outside_event_loop_thread(
monkeypatch, isolated_log_path, system_runtime
):
"""日志压缩 I/O 必须离开事件循环线程执行,避免大日志下载阻塞其他请求。"""
(isolated_log_path / "moviepilot.log").write_text("current", encoding="utf-8")
event_loop_thread = threading.current_thread().name
write_threads = []
original_write = zipfile.ZipFile.write
original_write = zipfile.ZipFile.writestr
def capture_write_thread(self, filename, arcname=None, compress_type=None, compresslevel=None):
def capture_write_thread(self, zinfo_or_arcname, data, compress_type=None, compresslevel=None):
"""记录实际 zip 写入线程,并保持原始 ZipFile.write 行为。"""
write_threads.append(threading.current_thread().name)
return original_write(
self,
filename,
arcname=arcname,
compress_type=compress_type,
compresslevel=compresslevel,
return original_write(self, zinfo_or_arcname, data, compress_type, compresslevel)
monkeypatch.setattr(zipfile.ZipFile, "writestr", capture_write_thread)
response = asyncio.run(
system_endpoint.download_logging(
name="moviepilot", _=SimpleNamespace(), runtime=system_runtime
)
monkeypatch.setattr(zipfile.ZipFile, "write", capture_write_thread)
response = asyncio.run(system_endpoint.download_logging(name="moviepilot", _=SimpleNamespace()))
)
body = asyncio.run(_read_streaming_body(response))
assert body

View File

@@ -46,7 +46,7 @@ _STUB_MODULES = dict([
_stub("app.application.site.sites", SitesHelper=_Dummy),
_stub("app.chain.media", MediaChain=_Dummy),
_stub("app.chain.mediaserver", MediaServerChain=_Dummy),
_stub("app.chain.search", SearchChain=_Dummy),
_stub("app.chain.search.facade", SearchChain=_Dummy),
_stub("app.chain.system", SystemChain=_Dummy),
_stub("app.runtime.events", eventmanager=_Dummy(), Event=_Dummy, EventManager=_Dummy),
_stub("app.domain.metainfo", MetaInfo=_Dummy),
@@ -116,16 +116,24 @@ class TestNettestSecurity:
"""
系统配置接口应分别返回 Rust 扩展可用性和当前实际启用状态。
"""
with patch.object(system_endpoint.rust_accel, "is_available", return_value=True), patch.object(
system_endpoint.rust_accel, "is_enabled", return_value=False
), patch.object(
system_endpoint.rust_accel, "is_required", return_value=True
), patch.object(
runtime = SimpleNamespace(
system=SimpleNamespace(
runtime_features=lambda: {
"RUST_ACCEL": True,
"RUST_ACCEL_AVAILABLE": True,
"RUST_ACCEL_ENABLED": False,
"RUST_ACCEL_REQUIRED": True,
}
)
)
with patch.object(
system_endpoint, "is_free_threaded_runtime", return_value=True
), patch.object(
system_endpoint, "is_gil_enabled", return_value=False
):
resp = asyncio.run(system_endpoint.get_env_setting(_="token"))
resp = asyncio.run(
system_endpoint.get_env_setting(_="token", runtime=runtime)
)
assert resp.success
assert resp.data["RUST_ACCEL_AVAILABLE"]
@@ -140,24 +148,29 @@ class TestNettestSecurity:
snapshot=Mock(return_value={}),
get=Mock(return_value=False),
)
runtime = SimpleNamespace(
system=SimpleNamespace(
user_global=AsyncMock(
return_value={
"USER_UNIQUE_ID": "user-id",
"SUBSCRIBE_SHARE_MANAGE": False,
"WORKFLOW_SHARE_MANAGE": False,
}
)
)
)
with patch.object(
system_endpoint, "get_runtime_settings", return_value=runtime_config
), patch.object(
system_endpoint.MoviePilotServerHelper,
"async_is_admin_user",
new=AsyncMock(return_value=False),
create=True,
), patch.object(
system_endpoint.MoviePilotServerHelper,
"get_user_uuid",
return_value="user-id",
create=True,
), patch.object(
system_endpoint, "is_free_threaded_runtime", return_value=True
), patch.object(
system_endpoint, "is_gil_enabled", return_value=False
):
resp = asyncio.run(system_endpoint.get_user_global_setting(_="token"))
resp = asyncio.run(
system_endpoint.get_user_global_setting(
_="token", runtime=runtime
)
)
assert resp.success
assert resp.data["PYTHON_FREE_THREADED"]
@@ -176,8 +189,6 @@ class TestNettestSecurity:
with patch.object(system_endpoint, "ImageHelper", return_value=image_helper), patch.object(
system_endpoint.HashUtils, "md5", return_value="etag", create=True
), patch.object(
system_endpoint.RequestUtils, "generate_cache_headers", return_value={}, create=True
):
resp = asyncio.run(
system_endpoint.fetch_image(
@@ -512,8 +523,6 @@ class TestNettestSecurity:
with patch.object(system_endpoint, "ImageHelper", return_value=image_helper), patch.object(
system_endpoint.HashUtils, "md5", return_value="etag", create=True
), patch.object(
system_endpoint.RequestUtils, "generate_cache_headers", return_value={}, create=True
), patch.object(
# is_safe_image_url_async 经 evaluate_url_safety_async 走异步解析
# _hostname_addresses_async(loop.getaddrinfo);必须 mock 异步版本,