Merged
fix(gateway): 可选渠道启动失败后关停仍以退出码 0 结束 #490
yechenzhenAdd on 1 day ago
fix(gateway): 可选渠道启动失败后关停仍以退出码 0 结束 #490
Merged
Total: 2 files changed+318-55
| @@ -431,6 +431,205 @@ async def test_other_single_channels_keep_one_task_and_disable(monkeypatch, plat | |||
| 431 | await _close(owner) | 431 | await _close(owner) |
| 432 | 432 | ||
| 433 | 433 | ||
| 434 | +async def _wait_done(task): | ||
| 435 | + async def wait(): | ||
| 436 | + while not task.done(): | ||
| 437 | + await asyncio.sleep(0.01) | ||
| 438 | + | ||
| 439 | + await asyncio.wait_for(wait(), timeout=5.0) | ||
| 440 | + | ||
| 441 | + | ||
| 442 | +@pytest.mark.parametrize('platform,class_name,config', [ | ||
| 443 | + ('telegram', 'TelegramChannel', {'enabled': True, 'bot_token': 'test-token'}), | ||
| 444 | + ('discord', 'DiscordChannel', {'enabled': True, 'bot_token': 'test-token'}), | ||
| 445 | + ('slack', 'SlackChannel', {'enabled': True, 'bot_token': 'test-token', 'app_token': 'test-app-token'}), | ||
| 446 | + ('whatsapp', 'WhatsAppChannel', {'enabled': True, 'bridge_url': 'ws://127.0.0.1:1'}), | ||
| 447 | + ('wecom', 'WecomChannel', {'enabled': True, 'bot_id': 'test-bot', 'secret': 'test-secret'}), | ||
| 448 | + ('wechat', 'WechatChannel', {'enabled': True}), | ||
| 449 | +]) | ||
| 450 | +async def test_shutdown_survives_a_channel_whose_start_failed(monkeypatch, platform, class_name, config): | ||
| 451 | + module = importlib.import_module(f'agent_gateway.channel_manager.im_platforms.{platform}.{platform}_connect') | ||
| 452 | + stopped = [] | ||
| 453 | + | ||
| 454 | + class Channel: | ||
| 455 | + channel_id = platform | ||
| 456 | + | ||
| 457 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 458 | + self.config = config | ||
| 459 | + self.on_message = Mock() | ||
| 460 | + | ||
| 461 | + async def start(self): | ||
| 462 | + raise RuntimeError(f'{platform} start failed: invalid token') | ||
| 463 | + | ||
| 464 | + async def stop(self): | ||
| 465 | + stopped.append(platform) | ||
| 466 | + | ||
| 467 | + monkeypatch.setattr(module, class_name, Channel) | ||
| 468 | + owner, manager = _owner() | ||
| 469 | + try: | ||
| 470 | + await manager.set_conf(platform, config) | ||
| 471 | + await _wait_done(getattr(owner, f'_{platform}_task')) | ||
| 472 | + await owner.stop_channels() | ||
| 473 | + assert stopped == [platform] | ||
| 474 | + finally: | ||
| 475 | + await _close(owner) | ||
| 476 | + | ||
| 477 | + | ||
| 478 | +@pytest.mark.parametrize('platform', ['feishu', 'xiaoyi']) | ||
| 479 | +async def test_shutdown_survives_app_channels_whose_start_failed(monkeypatch, platform): | ||
| 480 | + class_name = 'FeishuChannel' if platform == 'feishu' else 'XiaoyiChannel' | ||
| 481 | + module = importlib.import_module(f'agent_gateway.channel_manager.im_platforms.{platform}.{platform}_connect') | ||
| 482 | + stopped = [] | ||
| 483 | + | ||
| 484 | + class Channel: | ||
| 485 | + channel_id = platform | ||
| 486 | + | ||
| 487 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 488 | + self.config = config | ||
| 489 | + self.app_id = config.app_id if platform == 'feishu' else config.api_id | ||
| 490 | + self.on_message = Mock() | ||
| 491 | + | ||
| 492 | + async def start(self): | ||
| 493 | + raise RuntimeError(f'{platform} start failed') | ||
| 494 | + | ||
| 495 | + async def stop(self): | ||
| 496 | + stopped.append(self.app_id) | ||
| 497 | + | ||
| 498 | + monkeypatch.setattr(module, class_name, Channel) | ||
| 499 | + owner, manager = _owner() | ||
| 500 | + owner._im_inbound = SimpleNamespace(unregister_adapter=Mock()) | ||
| 501 | + owner._im_outbound = SimpleNamespace(unregister_adapter=Mock()) | ||
| 502 | + try: | ||
| 503 | + apps = [ | ||
| 504 | + {'enabled': True, 'app_id': name, 'app_secret': 'test-secret', 'ak': 'test-ak', 'sk': 'test-sk', 'agent_id': 'agent-1', 'api_id': name} | ||
| 505 | + for name in ('first', 'second') | ||
| 506 | + ] | ||
| 507 | + await manager.set_conf(platform, {'apps': apps}) | ||
| 508 | + channels = manager.get_channels_by_id(platform) | ||
| 509 | + assert len(channels) == 2 | ||
| 510 | + for channel in channels: | ||
| 511 | + await _wait_done(channel.start_task) | ||
| 512 | + await owner.stop_channels() | ||
| 513 | + assert sorted(stopped) == ['first', 'second'] | ||
| 514 | + finally: | ||
| 515 | + await _close(owner) | ||
| 516 | + | ||
| 517 | + | ||
| 518 | +async def test_shutdown_survives_enterprise_feishu_channels_whose_start_failed(monkeypatch): | ||
| 519 | + module = importlib.import_module('agent_gateway.channel_manager.im_platforms.feishu.feishu_connect') | ||
| 520 | + stopped = [] | ||
| 521 | + | ||
| 522 | + class Channel: | ||
| 523 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 524 | + self.config = config | ||
| 525 | + self.app_id = config.app_id | ||
| 526 | + self.channel_id = config.channel_id | ||
| 527 | + self.on_message = Mock() | ||
| 528 | + | ||
| 529 | + async def start(self): | ||
| 530 | + raise RuntimeError('feishu start failed') | ||
| 531 | + | ||
| 532 | + async def stop(self): | ||
| 533 | + stopped.append(self.app_id) | ||
| 534 | + | ||
| 535 | + monkeypatch.setattr(module, 'FeishuChannel', Channel) | ||
| 536 | + owner, manager = _owner() | ||
| 537 | + owner._im_inbound = SimpleNamespace(unregister_adapter=Mock()) | ||
| 538 | + owner._im_outbound = SimpleNamespace(unregister_adapter=Mock()) | ||
| 539 | + try: | ||
| 540 | + await manager.set_conf('feishu_enterprise', { | ||
| 541 | + 'bot-1': {'enabled': True, 'app_id': 'app-1', 'app_secret': 'test-secret'}, | ||
| 542 | + 'bot-2': {'enabled': True, 'app_id': 'app-2', 'app_secret': 'test-secret'}, | ||
| 543 | + }) | ||
| 544 | + tasks = list(owner._feishu_enterprise_tasks.values()) | ||
| 545 | + assert len(tasks) == 2 | ||
| 546 | + for task in tasks: | ||
| 547 | + await _wait_done(task) | ||
| 548 | + await owner.stop_channels() | ||
| 549 | + assert sorted(stopped) == ['app-1', 'app-2'] | ||
| 550 | + finally: | ||
| 551 | + await _close(owner) | ||
| 552 | + | ||
| 553 | + | ||
| 554 | +async def test_shutdown_stops_later_channels_after_an_earlier_start_failed(monkeypatch): | ||
| 555 | + telegram = importlib.import_module('agent_gateway.channel_manager.im_platforms.telegram.telegram_connect') | ||
| 556 | + discord = importlib.import_module('agent_gateway.channel_manager.im_platforms.discord.discord_connect') | ||
| 557 | + stopped = [] | ||
| 558 | + | ||
| 559 | + class FailedTelegram: | ||
| 560 | + channel_id = 'telegram' | ||
| 561 | + | ||
| 562 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 563 | + self.config = config | ||
| 564 | + self.on_message = Mock() | ||
| 565 | + | ||
| 566 | + async def start(self): | ||
| 567 | + raise RuntimeError('telegram start failed') | ||
| 568 | + | ||
| 569 | + async def stop(self): | ||
| 570 | + stopped.append('telegram') | ||
| 571 | + | ||
| 572 | + class RunningDiscord: | ||
| 573 | + channel_id = 'discord' | ||
| 574 | + | ||
| 575 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 576 | + self.config = config | ||
| 577 | + self.on_message = Mock() | ||
| 578 | + | ||
| 579 | + async def start(self): | ||
| 580 | + await asyncio.Event().wait() | ||
| 581 | + | ||
| 582 | + async def stop(self): | ||
| 583 | + stopped.append('discord') | ||
| 584 | + | ||
| 585 | + monkeypatch.setattr(telegram, 'TelegramChannel', FailedTelegram) | ||
| 586 | + monkeypatch.setattr(discord, 'DiscordChannel', RunningDiscord) | ||
| 587 | + owner, manager = _owner() | ||
| 588 | + try: | ||
| 589 | + await manager.set_conf('telegram', {'enabled': True, 'bot_token': 'test-token'}) | ||
| 590 | + await manager.set_conf('discord', {'enabled': True, 'bot_token': 'test-token'}) | ||
| 591 | + await _wait_done(owner._telegram_task) | ||
| 592 | + await owner.stop_channels() | ||
| 593 | + assert stopped == ['telegram', 'discord'] | ||
| 594 | + finally: | ||
| 595 | + await _close(owner) | ||
| 596 | + | ||
| 597 | + | ||
| 598 | +async def test_shutdown_clears_ssh_key_issuer_after_ssh_start_failed(monkeypatch): | ||
| 599 | + module = importlib.import_module('agent_gateway.channel_manager.protocol.ssh.ssh_connect') | ||
| 600 | + from agent_gateway.common import config as config_module | ||
| 601 | + | ||
| 602 | + monkeypatch.setattr(config_module, 'get_config', lambda: {'gateway': {'agent_client': {'type': 'agentos_router'}}}) | ||
| 603 | + stopped = [] | ||
| 604 | + | ||
| 605 | + class Channel: | ||
| 606 | + channel_id = 'ssh' | ||
| 607 | + | ||
| 608 | + def __init__(self, config, bus, *, key_registry): | ||
| 609 | + self.config = config | ||
| 610 | + self.key_registry = key_registry | ||
| 611 | + self.key_issuer = object() | ||
| 612 | + self.on_message = Mock() | ||
| 613 | + | ||
| 614 | + async def start(self): | ||
| 615 | + raise RuntimeError('ssh start failed') | ||
| 616 | + | ||
| 617 | + async def stop(self): | ||
| 618 | + stopped.append('ssh') | ||
| 619 | + | ||
| 620 | + monkeypatch.setattr(module, 'SshChannel', Channel) | ||
| 621 | + owner, manager = _owner() | ||
| 622 | + try: | ||
| 623 | + await manager.set_conf('ssh', {'enabled': True, 'listen_port': 2222, 'auth': {'enabled': True}}) | ||
| 624 | + await _wait_done(owner._ssh_task) | ||
| 625 | + owner._agent_server_ext.set_key_issuer.reset_mock() | ||
| 626 | + await owner.stop_channels() | ||
| 627 | + assert stopped == ['ssh'] | ||
| 628 | + owner._agent_server_ext.set_key_issuer.assert_called_once_with(None, ephemeral_key_ttl_sec=300.0) | ||
| 629 | + finally: | ||
| 630 | + await _close(owner) | ||
| 631 | + | ||
| 632 | + | ||
| 434 | async def test_ssh_key_issuer_injection_and_removal_are_preserved(monkeypatch): | 633 | async def test_ssh_key_issuer_injection_and_removal_are_preserved(monkeypatch): |
| 435 | module = importlib.import_module('agent_gateway.channel_manager.protocol.ssh.ssh_connect') | 634 | module = importlib.import_module('agent_gateway.channel_manager.protocol.ssh.ssh_connect') |
| 436 | from agent_gateway.common import config as config_module | 635 | from agent_gateway.common import config as config_module |
| @@ -693,6 +892,92 @@ async def test_single_retains_optional_startup_and_shutdown_stage_boundaries(mon | |||
| 693 | ] | 892 | ] |
| 694 | 893 | ||
| 695 | 894 | ||
| 895 | +async def test_single_shutdown_still_stops_services_after_a_channel_start_failed(monkeypatch): | ||
| 896 | + from agent_gateway.application import single | ||
| 897 | + from agent_gateway.application.optional_channels import OptionalChannels | ||
| 898 | + from agent_gateway.common import config as config_module | ||
| 899 | + from agent_gateway.cron import proactive_cron_sync | ||
| 900 | + | ||
| 901 | + events = [] | ||
| 902 | + shutdown = asyncio.Event() | ||
| 903 | + manager = ChannelManager(SimpleNamespace()) | ||
| 904 | + manager.pop_channels_by_id = Mock(return_value=[]) | ||
| 905 | + services = SimpleNamespace( | ||
| 906 | + credential_access=object(), auth_service_provider=lambda: None, credential_update_sink=object(), | ||
| 907 | + client=object(), third_agent=object(), agent_server_ext=SimpleNamespace(set_key_issuer=Mock()), | ||
| 908 | + extension_registry=object(), message_handler=object(), im_inbound=object(), im_outbound=object(), | ||
| 909 | + cron_scheduler=object(), cron_controller=object(), heartbeat_controller=object(), | ||
| 910 | + heartbeat_service=object(), config_updater=None, channel_manager=manager, | ||
| 911 | + updater_service=object(), initial_channels_conf={}, full_cfg={}, | ||
| 912 | + stop=AsyncMock(side_effect=lambda: events.append('services.stop')), | ||
| 913 | + start_preparation=Mock(), | ||
| 914 | + ) | ||
| 915 | + monkeypatch.setattr(single, 'assemble_services', AsyncMock(return_value=services)) | ||
| 916 | + web = SimpleNamespace(stop=AsyncMock(side_effect=lambda: events.append('web.stop'))) | ||
| 917 | + homepage = asyncio.Event() | ||
| 918 | + homepage.set() | ||
| 919 | + monkeypatch.setattr(single, 'assemble_web', Mock(return_value=(web, homepage))) | ||
| 920 | + | ||
| 921 | + async def start_web(*args): | ||
| 922 | + events.append('web.ready') | ||
| 923 | + return asyncio.create_task(asyncio.Event().wait()) | ||
| 924 | + | ||
| 925 | + monkeypatch.setattr(single, 'start_web_core', start_web) | ||
| 926 | + runtime = SimpleNamespace(start=AsyncMock(side_effect=lambda: events.append('protocol.ready')), wait_until_closed=asyncio.Event().wait) | ||
| 927 | + tui = SimpleNamespace(protocol_runtime=runtime, stop=AsyncMock()) | ||
| 928 | + monkeypatch.setattr(single, 'assemble_tui_acp', AsyncMock(return_value=tui)) | ||
| 929 | + monkeypatch.setattr(config_module, 'get_config', lambda: {}) | ||
| 930 | + monkeypatch.setattr(proactive_cron_sync, 'sync_proactive_tick_job', AsyncMock()) | ||
| 931 | + monkeypatch.setattr(single, 'shutdown_gateway_telemetry', AsyncMock(side_effect=lambda: events.append('telemetry.stop'))) | ||
| 932 | + | ||
| 933 | + owners = [] | ||
| 934 | + | ||
| 935 | + class Channels(OptionalChannels): | ||
| 936 | + def __init__(self, **kwargs): | ||
| 937 | + super().__init__(**kwargs) | ||
| 938 | + owners.append(self) | ||
| 939 | + | ||
| 940 | + monkeypatch.setattr(single, 'OptionalChannels', Channels) | ||
| 941 | + telegram = importlib.import_module('agent_gateway.channel_manager.im_platforms.telegram.telegram_connect') | ||
| 942 | + stopped = [] | ||
| 943 | + | ||
| 944 | + class Channel: | ||
| 945 | + channel_id = 'telegram' | ||
| 946 | + | ||
| 947 | + def __init__(self, config, bus, *, im_platform_adapter=None): | ||
| 948 | + self.config = config | ||
| 949 | + self.on_message = Mock() | ||
| 950 | + | ||
| 951 | + async def start(self): | ||
| 952 | + raise RuntimeError('telegram start failed: invalid token') | ||
| 953 | + | ||
| 954 | + async def stop(self): | ||
| 955 | + stopped.append('telegram') | ||
| 956 | + | ||
| 957 | + monkeypatch.setattr(telegram, 'TelegramChannel', Channel) | ||
| 958 | + restart_gateway = Mock() | ||
| 959 | + | ||
| 960 | + async def run(): | ||
| 961 | + await single.run_single( | ||
| 962 | + 'ws://example/ws', '127.0.0.1', 0, '/ws', shutdown, | ||
| 963 | + config_saved_factory=Mock(), restart_gateway=restart_gateway, process_start_t0=0.0, | ||
| 964 | + startup_import_phases=[], preprocessor=SimpleNamespace(with_credential_access=lambda access: object()), connect_with_retry=AsyncMock(), | ||
| 965 | + ) | ||
| 966 | + | ||
| 967 | + run_task = asyncio.create_task(run()) | ||
| 968 | + while 'protocol.ready' not in events: | ||
| 969 | + await asyncio.sleep(0.01) | ||
| 970 | + await manager.set_conf('telegram', {'enabled': True, 'bot_token': 'test-token'}) | ||
| 971 | + await _wait_done(owners[0]._telegram_task) | ||
| 972 | + shutdown.set() | ||
| 973 | + await asyncio.wait_for(run_task, timeout=10) | ||
| 974 | + | ||
| 975 | + assert stopped == ['telegram'] | ||
| 976 | + assert events == ['web.ready', 'protocol.ready', 'web.stop', 'services.stop', 'telemetry.stop'] | ||
| 977 | + services.stop.assert_awaited_once() | ||
| 978 | + restart_gateway.assert_not_called() | ||
| 979 | + | ||
| 980 | + | ||
| 696 | async def test_web_proxy_reconfiguration_closes_old_resources_and_preserves_web_shutdown(monkeypatch): | 981 | async def test_web_proxy_reconfiguration_closes_old_resources_and_preserves_web_shutdown(monkeypatch): |
| 697 | from agent_gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig | 982 | from agent_gateway.channel_manager.web.web_connect import WebChannel, WebChannelConfig |
| 698 | from agent_gateway.channel_manager.web.app_web_handlers import _DummyBus | 983 | from agent_gateway.channel_manager.web.app_web_handlers import _DummyBus |