Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/core/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,9 @@ async def _load(self) -> None:
# 唯一加载流程串行导入,禁用时不会到达这里。
package = await self._in_thread(importlib.import_module, "fastapi_mcp")
self._check_open()
from app.services.common import telemetry

telemetry.enable_mcp_integration()
await self._stage("building")
import httpx

Expand Down
46 changes: 41 additions & 5 deletions app/services/common/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

if TYPE_CHECKING:
from sentry_sdk._types import EventProcessor, TransactionProcessor
from sentry_sdk.integrations import Integration

from app.models.schema import WSTaskScriptStartedData
from app.models.task import ScriptItem, TaskItem, TaskMode, TaskTriggerReason
Expand Down Expand Up @@ -82,6 +83,7 @@
_sentry_release: str | None = None
_sentry_dist: str | None = None
_sentry_started = False
_mcp_loaded = False

NOISY_TRANSACTIONS = {
"/api/core/health",
Expand Down Expand Up @@ -326,6 +328,23 @@ def _start_sentry(release: str, dist: str | None = None) -> None:

global _sentry_started

from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.httpx import HttpxIntegration
from sentry_sdk.integrations.starlette import StarletteIntegration

# 保留现有 Web 与日志采集,避免自动探测在监听前导入可选 MCP 服务。
integrations: list[Integration] = [
LoggingIntegration(level=None, event_level=None, sentry_logs_level=None),
LoguruIntegration(level=None, event_level=30, sentry_logs_level=None),
FastApiIntegration(),
StarletteIntegration(),
HttpxIntegration(),
]
if _mcp_loaded:
from sentry_sdk.integrations.mcp import MCPIntegration

integrations.append(MCPIntegration())

sentry_sdk.init(
dsn=SENTRY_DSN,
release=f"auto-mas@{release}",
Expand All @@ -336,10 +355,8 @@ def _start_sentry(release: str, dist: str | None = None) -> None:
include_source_context=False,
max_request_body_size="never",
server_name="AUTO-MAS",
integrations=[
LoggingIntegration(level=None, event_level=None, sentry_logs_level=None),
LoguruIntegration(level=None, event_level=30, sentry_logs_level=None),
],
auto_enabling_integrations=False,
integrations=integrations,
traces_sampler=sample_trace,
# 脱敏原地处理 SDK 的 JSON 事件;TypedDict 回调与通用字典实现共用同一对象。
before_send=cast("EventProcessor", sanitize_event),
Expand All @@ -348,6 +365,25 @@ def _start_sentry(release: str, dist: str | None = None) -> None:
_sentry_started = True


def enable_mcp_integration() -> None:
"""MCP 实际加载后安装诊断集成,遥测关闭时只记住已加载状态。"""
global _mcp_loaded

_mcp_loaded = True
if not _sentry_started:
return

from sentry_sdk.integrations import setup_integrations
from sentry_sdk.integrations.mcp import MCPIntegration

client = sentry_sdk.get_client()
client.integrations.update(
setup_integrations(
[MCPIntegration()], with_defaults=False, options=client.options
)
)


def _resolve_transaction_path(
sampling_context: dict[str, Any], name: Any
) -> str | None:
Expand Down Expand Up @@ -398,7 +434,7 @@ def set_telemetry_enabled(enabled: bool) -> None:
if not enabled:
if _sentry_started:
sentry_sdk.get_client().close(timeout=0)
sentry_sdk.init(dsn=None)
sentry_sdk.init(dsn=None, auto_enabling_integrations=False)
_sentry_started = False
return

Expand Down
24 changes: 6 additions & 18 deletions app/task/Okww/AutoProxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,20 @@
from app.utils.common.log import sources as log_source

from . import push_log as _push_log
from .tools import async_switch_account
from .tools.account_switch import async_switch_account
from .tools.backup_archive import (
archive_mas_runtime_backup,
mas_config_dir,
owner_for_mode,
read_overlay_values,
)
from .tools.batch_logs import (
NATIVE_SWITCH_UNSUPPORTED_MESSAGE,
NativeSwitchUnsupportedError,
)
from .tools.config_paths import (
_OKWW_REL_CONFIG_DIR,
_okww_config_base,
_okww_mas_config_dir,
)
from .tools.game_update import update_game_via_launcher
from .tools.launcher_start import (
async_start_game_via_launcher,
Expand Down Expand Up @@ -131,7 +134,6 @@
# ⚠️ 与前端 OkwwScriptEdit.vue 的 OKWW_EXE_NAME 保持同步,改这里时需同步改前端
_OKWW_REL_EXE = "ok-ww.exe"
_OKWW_REL_APP_JSON = "data/apps/ok-ww/app.json"
_OKWW_REL_CONFIG_DIR = "data/apps/ok-ww/working/configs"
_OKWW_REL_LOG_FILE = "data/apps/ok-ww/working/logs/ok-script.log"
_OKWW_REL_PYTHONW = "data/apps/ok-ww/python/pythonw.exe"
_OKWW_TRACK_PROCESS_NAME = "pythonw.exe"
Expand Down Expand Up @@ -159,20 +161,6 @@ def _daily_task_argument(script_root: Path) -> str:
return "DailyTask" if version >= Version("3.6.7b2") else "1"


def _okww_config_base(raw: object) -> str:
"""读取 OK-WW 配置来源(base 三态),并兼容旧版字面量。"""

return _utils_constants.normalize_base_source(raw) or _utils_constants.BASE_SHARED


def _okww_mas_config_dir(script_id: str, user_id: str, base: str) -> Path:
base = _okww_config_base(base)
owner = owner_for_mode(base, user_id)
if owner is None:
raise ValueError("原生来源不使用 MAS 全量配置目录")
return mas_config_dir(script_id, owner)


def _okww_error_status(log: str) -> str | None:
"""从上游错误日志读取可显示的失败原因。"""
error = _OKWW_ERROR_LOG.search(log)
Expand Down
3 changes: 2 additions & 1 deletion app/task/Okww/BatchProxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from app.utils import io as _utils_io

from . import push_log
from .AutoProxy import _OKWW_ERROR_PREFIX, AutoProxyTask, _okww_mas_config_dir
from .AutoProxy import _OKWW_ERROR_PREFIX, AutoProxyTask
from .tools.batch_config import (
DAILY_TASK,
completed_accounts,
Expand All @@ -24,6 +24,7 @@
account_log_context,
native_switch_unsupported,
)
from .tools.config_paths import _okww_mas_config_dir

logger = get_logger("OK-WW 批次")
_BATCH_FAILURE_LOG = "MultiAccountConfigTask:info_set 状态 执行失败"
Expand Down
8 changes: 5 additions & 3 deletions app/task/Okww/ScriptConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,20 @@
from app.utils import io as _utils_io

from .AutoProxy import (
_OKWW_REL_CONFIG_DIR,
_OKWW_REL_EXE,
_OKWW_REL_PYTHONW,
_configure_okww_launcher,
_okww_config_base,
_okww_mas_config_dir,
)
from .tools.backup_archive import (
archive_mas_runtime_backup,
owner_for_mode,
read_overlay_values,
)
from .tools.config_paths import (
_OKWW_REL_CONFIG_DIR,
_okww_config_base,
_okww_mas_config_dir,
)

logger = get_logger("OK-WW 脚本设置")

Expand Down
3 changes: 1 addition & 2 deletions app/task/Okww/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,13 @@

from .AutoProxy import (
_OKWW_REL_APP_JSON,
_OKWW_REL_CONFIG_DIR,
_OKWW_REL_EXE,
AutoProxyTask,
_okww_config_base,
)
from .BatchProxy import BatchProxyTask
from .ScriptConfig import ScriptConfigTask
from .tools.backup_archive import archive_native_backup
from .tools.config_paths import _OKWW_REL_CONFIG_DIR, _okww_config_base
from .Update import WuwaUpdateTask

logger = get_logger("OK-WW 调度器")
Expand Down
4 changes: 1 addition & 3 deletions app/task/Okww/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,4 @@
# You should have received a copy of the GNU Affero General Public License
# along with AUTO-MAS. If not, see <https://www.gnu.org/licenses/>.

from .account_switch import account_switch, async_switch_account

__all__ = ["account_switch", "async_switch_account"]
"""OK-WW 工具包;调用方直接导入所需模块。"""
10 changes: 5 additions & 5 deletions app/task/Okww/tools/config_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,16 @@
from app.utils import BASE_INDEPENDENT, BASE_NATIVE, BASE_SHARED, get_logger
from app.utils import io as _utils_io

from ..AutoProxy import (
_OKWW_REL_CONFIG_DIR,
_okww_config_base,
_okww_mas_config_dir,
)
from .backup_archive import (
mas_rollback_point,
read_overlay_values,
restore_mas_backup,
)
from .config_paths import (
_OKWW_REL_CONFIG_DIR,
_okww_config_base,
_okww_mas_config_dir,
)

logger = get_logger("OK-WW 配置目录")

Expand Down
22 changes: 22 additions & 0 deletions app/task/Okww/tools/config_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""OK-WW 配置来源与目录;配置操作不依赖任务执行器。"""

from pathlib import Path

from app.utils import constants as _utils_constants

from .backup_archive import mas_config_dir, owner_for_mode

_OKWW_REL_CONFIG_DIR = "data/apps/ok-ww/working/configs"


def _okww_config_base(raw: object) -> str:
"""读取 OK-WW 配置来源(base 三态),并兼容旧版字面量。"""
return _utils_constants.normalize_base_source(raw) or _utils_constants.BASE_SHARED


def _okww_mas_config_dir(script_id: str, user_id: str, base: str) -> Path:
base = _okww_config_base(base)
owner = owner_for_mode(base, user_id)
if owner is None:
raise ValueError("原生来源不使用 MAS 全量配置目录")
return mas_config_dir(script_id, owner)
2 changes: 1 addition & 1 deletion app/task/Okww/tools/restore_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@

from app.utils.common.config import restore as _utils_config_restore

from ..AutoProxy import _OKWW_REL_CONFIG_DIR, _okww_config_base
from .backup_archive import (
build_backup_file_summary,
build_overlay_summary,
Expand All @@ -56,6 +55,7 @@
restore_mas_backup,
restore_native_backup,
)
from .config_paths import _OKWW_REL_CONFIG_DIR, _okww_config_base


def _user_guard(ctx: _utils_config_restore.RestoreContext) -> None:
Expand Down
3 changes: 3 additions & 0 deletions changelog.d/cnb287-startup-imports.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
project: runtime

减少后端启动等待,缓解部分设备启动超时的问题。
4 changes: 3 additions & 1 deletion tests/task/test_builtin_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ async def cleanup(sid):
)


def test_cold_declarations_and_parent_packages_do_not_load_execution_or_config(
def test_cold_declarations_and_okww_config_do_not_load_execution_or_config(
tmp_path,
):
root = Path(__file__).resolve().parents[2]
Expand All @@ -259,6 +259,8 @@ def test_cold_declarations_and_parent_packages_do_not_load_execution_or_config(
with patch("asyncio.create_task",side_effect=AssertionError("spawn")):
for folder in folders:
importlib.import_module("app.task."+folder+".registration")
from app.task.Okww.registration import build_config_handler
build_config_handler()
forbidden = [n for n in sys.modules if n in {"app.core.config.manager","app.core.task_manager"} or (n.startswith("app.task.") and (n.endswith((".manager",".embedded_manager",".restore_service",".AutoProxy")) or ".tools.core.runner" in n))]
assert not forbidden, forbidden
assert not __import__("pathlib").Path("config").exists()
Expand Down
69 changes: 69 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
Expand Down Expand Up @@ -118,5 +121,71 @@ def test_disabled_telemetry_skips_sentry(self) -> None:
start_sentry.assert_not_called()


def test_sentry_defers_mcp_without_losing_integrations_or_telemetry_toggle(tmp_path):
"""真实 SDK 的冷启动不加载 MCP,加载后的采集在开关切换后仍有效。"""
root = Path(__file__).resolve().parents[1]
code = r"""
import json, sys
import sentry_sdk
from sentry_sdk.transport import Transport
from app.services.common import telemetry

events = []
class LocalTransport(Transport):
def capture_envelope(self, envelope):
event = envelope.get_event()
if event is not None:
events.append(event)

original_init = sentry_sdk.init
def init_local(*args, **kwargs):
if kwargs.get("dsn"):
kwargs["transport"] = LocalTransport
return original_init(*args, **kwargs)
sentry_sdk.init = init_local

telemetry.init_sentry(release="v0.0.0", development=False, enabled=True)
expected = {"fastapi", "starlette", "httpx", "logging", "loguru"}
assert expected <= sentry_sdk.get_client().integrations.keys()
assert "mcp" not in sys.modules and "fastapi_mcp" not in sys.modules
sentry_sdk.capture_event({
"message": "startup check",
"user": {"id": "PRIVATE_VALUE_FOR_STARTUP_CHECK"},
"extra": {"value": "PRIVATE_VALUE_FOR_STARTUP_CHECK"},
"request": {"url": "http://localhost/api/check", "headers": {"authorization": "PRIVATE_VALUE_FOR_STARTUP_CHECK"}},
})
assert len(events) == 1
assert "user" not in events[0] and "extra" not in events[0]
assert "PRIVATE_VALUE_FOR_STARTUP_CHECK" not in json.dumps(events[0])
telemetry.set_telemetry_enabled(False)
assert sentry_sdk.get_client().transport is None
assert "mcp" not in sys.modules
telemetry.set_telemetry_enabled(True)
assert expected <= sentry_sdk.get_client().integrations.keys()
assert "mcp" not in sys.modules

import fastapi_mcp
telemetry.enable_mcp_integration()
assert "mcp" in sentry_sdk.get_client().integrations
telemetry.set_telemetry_enabled(False)
telemetry.enable_mcp_integration()
assert sentry_sdk.get_client().transport is None
telemetry.set_telemetry_enabled(True)
assert expected | {"mcp"} <= sentry_sdk.get_client().integrations.keys()
telemetry.set_telemetry_enabled(False)
print(json.dumps({"ok": True}))
"""
result = subprocess.run(
[sys.executable, "-c", code],
cwd=tmp_path,
env={**os.environ, "PYTHONPATH": str(root), "SENTRY_DSN": ""},
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stdout + result.stderr
assert json.loads(result.stdout) == {"ok": True}


if __name__ == "__main__":
unittest.main()