Merged
fix(cron): 隔离 Gateway 定时任务存储 #492
XinchenZAdd on 2 days ago
fix(cron): 隔离 Gateway 定时任务存储 #492
Merged
Total: 10 files changed+211-24
| @@ -4350,6 +4350,7 @@ class MessageHandler(ABC): | |||
| 4350 | cc = self._cron_controller | 4350 | cc = self._cron_controller |
| 4351 | if cc is None: | 4351 | if cc is None: |
| 4352 | return | 4352 | return |
| 4353 | + session_id = self._stream_sessions.get(request_id) or session_id | ||
| 4353 | action = str(payload.get("action") or "").strip() | 4354 | action = str(payload.get("action") or "").strip() |
| 4354 | command_id = str(payload.get("command_id") or "").strip() | 4355 | command_id = str(payload.get("command_id") or "").strip() |
| 4355 | params = payload.get("data") or {} | 4356 | params = payload.get("data") or {} |
| @@ -4436,6 +4437,22 @@ class MessageHandler(ABC): | |||
| 4436 | return job | 4437 | return job |
| 4437 | 4438 | ||
| 4438 | try: | 4439 | try: |
| 4440 | + # Only the originating server-side route may identify a cron session. | ||
| 4441 | + if channel_id == "__cron__" or ( | ||
| 4442 | + session_id and session_id.startswith(("__cron__", "cron_")) | ||
| 4443 | + ): | ||
| 4444 | + raise PermissionError("Cron commands are unavailable in cron execution sessions") | ||
| 4445 | + if session_id: | ||
| 4446 | + from agent_gateway.common.external_providers import provider | ||
| 4447 | + from e2a.provider_domains import PROVIDER_DOMAIN_SESSION_METADATA | ||
| 4448 | + | ||
| 4449 | + session_metadata = await provider( | ||
| 4450 | + PROVIDER_DOMAIN_SESSION_METADATA | ||
| 4451 | + ).get_session_metadata_async( | ||
| 4452 | + session_id, enable_writeback=False, user_id=owner_user_id or None, | ||
| 4453 | + ) | ||
| 4454 | + if session_metadata.get("cron_id"): | ||
| 4455 | + raise PermissionError("Cron commands are unavailable in cron execution sessions") | ||
| 4439 | if action == "list": | 4456 | if action == "list": |
| 4440 | # 无 user 时传空串,只列空身份任务,不传 None(None 会跳过用户维, | 4457 | # 无 user 时传空串,只列空身份任务,不传 None(None 会跳过用户维, |
| 4441 | # 把本机其他用户的任务也列出来)。有 user 时按属主筛。 | 4458 | # 把本机其他用户的任务也列出来)。有 user 时按属主筛。 |
| @@ -7,6 +7,7 @@ | |||
| 7 | 7 | ||
| 8 | from __future__ import annotations | 8 | from __future__ import annotations |
| 9 | 9 | ||
| 10 | +import asyncio | ||
| 10 | import logging | 11 | import logging |
| 11 | from typing import Any | 12 | from typing import Any |
| 12 | 13 | ||
| @@ -15,6 +16,7 @@ from agent_gateway.common.cron_settings import ( # noqa: F401 | |||
| 15 | load_cron_store_settings, | 16 | load_cron_store_settings, |
| 16 | ) | 17 | ) |
| 17 | from agent_gateway.runtime.cron.etcd_store import EtcdCronJobStore | 18 | from agent_gateway.runtime.cron.etcd_store import EtcdCronJobStore |
| 19 | +from agent_gateway.runtime.cron.file_migration import migrate_legacy_cron_files | ||
| 18 | from agent_gateway.runtime.cron.store import FileCronJobStore | 20 | from agent_gateway.runtime.cron.store import FileCronJobStore |
| 19 | from agent_gateway.runtime.cron.store_base import CronJobStoreBackend | 21 | from agent_gateway.runtime.cron.store_base import CronJobStoreBackend |
| 20 | 22 | ||
| @@ -39,10 +41,10 @@ async def create_gateway_cron_store( | |||
| 39 | except Exception: | 41 | except Exception: |
| 40 | config = {} | 42 | config = {} |
| 41 | settings = load_cron_store_settings(config) | 43 | settings = load_cron_store_settings(config) |
| 42 | - # FileCronJobStore 自带 path 缺省回落(store 内 get_cron_jobs_path 兜底) | ||
| 43 | - path = settings.file_path | ||
| 44 | if settings.backend != "etcd": | 44 | if settings.backend != "etcd": |
| 45 | - return FileCronJobStore(path=path) | 45 | + store = FileCronJobStore(path=settings.file_path) |
| 46 | + await asyncio.to_thread(migrate_legacy_cron_files, store.path) | ||
| 47 | + return store | ||
| 46 | 48 | ||
| 47 | if not settings.endpoints: | 49 | if not settings.endpoints: |
| 48 | logger.error( | 50 | logger.error( |
| @@ -0,0 +1,48 @@ | |||
| 1 | +"""Import the shared cron files once, before opening the Gateway file store.""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import json | ||
| 6 | +import os | ||
| 7 | +import tempfile | ||
| 8 | +from pathlib import Path | ||
| 9 | + | ||
| 10 | +import portalocker | ||
| 11 | + | ||
| 12 | +from agent_gateway.common.paths import get_legacy_cron_jobs_path | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def migrate_legacy_cron_files(destination: Path) -> None: | ||
| 16 | + """Initialize the authoritative file and lifecycle registry atomically per file.""" | ||
| 17 | + if destination.exists() and destination.with_name("cron_lifecycle_owners.json").exists(): | ||
| 18 | + return | ||
| 19 | + | ||
| 20 | + legacy = get_legacy_cron_jobs_path() | ||
| 21 | + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) | ||
| 22 | + with portalocker.Lock(str(destination) + ".migration.lock", timeout=10): | ||
| 23 | + for source, target, key in ( | ||
| 24 | + (legacy, destination, "jobs"), | ||
| 25 | + ( | ||
| 26 | + legacy.with_name("cron_lifecycle_owners.json"), | ||
| 27 | + destination.with_name("cron_lifecycle_owners.json"), | ||
| 28 | + "owners", | ||
| 29 | + ), | ||
| 30 | + ): | ||
| 31 | + if target.exists(): | ||
| 32 | + continue | ||
| 33 | + try: | ||
| 34 | + content = source.read_bytes() | ||
| 35 | + except FileNotFoundError: | ||
| 36 | + content = json.dumps({key: []}).encode() | ||
| 37 | + data = json.loads(content) | ||
| 38 | + if not isinstance(data, dict) or not isinstance(data.get(key), list): | ||
| 39 | + raise ValueError(f"Invalid legacy cron data in {source}") | ||
| 40 | + # Stage beside the target so publishing stays on the same filesystem. | ||
| 41 | + with tempfile.TemporaryDirectory(dir=target.parent) as staging_dir: | ||
| 42 | + staged = Path(staging_dir) / target.name | ||
| 43 | + staged.touch(mode=0o600) | ||
| 44 | + with staged.open("wb") as stream: | ||
| 45 | + stream.write(content) | ||
| 46 | + stream.flush() | ||
| 47 | + os.fsync(stream.fileno()) | ||
| 48 | + staged.replace(target) | ||
| @@ -0,0 +1,59 @@ | |||
| 1 | +import json | ||
| 2 | + | ||
| 3 | +import pytest | ||
| 4 | + | ||
| 5 | +from agent_gateway.runtime.cron import file_migration | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +def test_migrates_both_cron_files_once(tmp_path, monkeypatch): | ||
| 9 | + old = tmp_path / "agent" / "cron_jobs.json" | ||
| 10 | + new = tmp_path / "gateway" / "cron" / "cron_jobs.json" | ||
| 11 | + old.parent.mkdir() | ||
| 12 | + old.write_text('{"jobs":[{"id":"existing","last_session_id":"web_old"}]}') | ||
| 13 | + old.with_name("cron_lifecycle_owners.json").write_text('{"owners":["owner"]}') | ||
| 14 | + monkeypatch.setattr(file_migration, "get_legacy_cron_jobs_path", lambda: old) | ||
| 15 | + | ||
| 16 | + file_migration.migrate_legacy_cron_files(new) | ||
| 17 | + assert json.loads(new.read_bytes())["jobs"] == [ | ||
| 18 | + {"id": "existing", "last_session_id": "web_old"}, | ||
| 19 | + ] | ||
| 20 | + assert json.loads(new.with_name("cron_lifecycle_owners.json").read_bytes()) == { | ||
| 21 | + "owners": ["owner"], | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + old.write_text('{"jobs":[]}') | ||
| 25 | + file_migration.migrate_legacy_cron_files(new) | ||
| 26 | + assert json.loads(new.read_bytes())["jobs"][0]["id"] == "existing" | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def test_invalid_legacy_data_does_not_bypass_startup(tmp_path, monkeypatch): | ||
| 30 | + old = tmp_path / "legacy.json" | ||
| 31 | + new = tmp_path / "gateway" / "cron_jobs.json" | ||
| 32 | + old.write_text('{"jobs":null}') | ||
| 33 | + monkeypatch.setattr(file_migration, "get_legacy_cron_jobs_path", lambda: old) | ||
| 34 | + | ||
| 35 | + with pytest.raises(ValueError, match="Invalid legacy cron data"): | ||
| 36 | + file_migration.migrate_legacy_cron_files(new) | ||
| 37 | + | ||
| 38 | + assert not new.exists() | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def test_failed_sync_cleans_staging_and_allows_retry(tmp_path, monkeypatch): | ||
| 42 | + old = tmp_path / "legacy.json" | ||
| 43 | + new = tmp_path / "gateway" / "cron_jobs.json" | ||
| 44 | + payload = b'{"jobs":[{"id":"existing"}]}' | ||
| 45 | + old.write_bytes(payload) | ||
| 46 | + monkeypatch.setattr(file_migration, "get_legacy_cron_jobs_path", lambda: old) | ||
| 47 | + | ||
| 48 | + def fail_sync(_fd): | ||
| 49 | + raise OSError("sync failed") | ||
| 50 | + | ||
| 51 | + with monkeypatch.context() as patch: | ||
| 52 | + patch.setattr(file_migration.os, "fsync", fail_sync) | ||
| 53 | + with pytest.raises(OSError, match="sync failed"): | ||
| 54 | + file_migration.migrate_legacy_cron_files(new) | ||
| 55 | + | ||
| 56 | + assert not new.exists() | ||
| 57 | + assert not any(path.is_dir() for path in new.parent.iterdir()) | ||
| 58 | + file_migration.migrate_legacy_cron_files(new) | ||
| 59 | + assert new.read_bytes() == payload | ||
Mtests/unit_tests/gateway/test_cron_scheduler.py+1-1File content is under review, please try again later
| @@ -21,6 +21,16 @@ from agent_gateway.cron.controller import CronController | |||
| 21 | from agent_gateway.message_handler import message_handler as mh | 21 | from agent_gateway.message_handler import message_handler as mh |
| 22 | from agent_gateway.message_handler.message_handler import MessageHandler | 22 | from agent_gateway.message_handler.message_handler import MessageHandler |
| 23 | 23 | ||
| 24 | +@pytest.fixture(autouse=True) | ||
| 25 | +def session_metadata_provider(monkeypatch): | ||
| 26 | + lookup = AsyncMock(return_value={}) | ||
| 27 | + monkeypatch.setattr( | ||
| 28 | + "agent_gateway.common.external_providers.provider", | ||
| 29 | + lambda _: SimpleNamespace(get_session_metadata_async=lookup), | ||
| 30 | + ) | ||
| 31 | + return lookup | ||
| 32 | + | ||
| 33 | + | ||
| 24 | 34 | ||
| 25 | def _make_controller() -> CronController: | 35 | def _make_controller() -> CronController: |
| 26 | store = SimpleNamespace( | 36 | store = SimpleNamespace( |
| @@ -179,6 +189,7 @@ async def test_delete_job_force_path_still_serves_auto_sync() -> None: | |||
| 179 | 189 | ||
| 180 | def _bare_handler() -> MessageHandler: | 190 | def _bare_handler() -> MessageHandler: |
| 181 | handler = object.__new__(MessageHandler) | 191 | handler = object.__new__(MessageHandler) |
| 192 | + handler._stream_sessions = {} | ||
| 182 | handler.agent_client = SimpleNamespace() | 193 | handler.agent_client = SimpleNamespace() |
| 183 | handler._stream_metadata = {} | 194 | handler._stream_metadata = {} |
| 184 | handler._stream_modes = {} | 195 | handler._stream_modes = {} |
Mtests/unit_tests/gateway/test_cron_store_path_resolution.py+21-17File content is under review, please try again later
Mtests/unit_tests/gateway/test_message_handler_cron_push.py+36-0File content is under review, please try again later