Просмотр исходного кода

fix: honor idle cleanup settings during anti-ban rest

unknown 3 недель назад
Родитель
Сommit
f1ec903395
2 измененных файлов с 233 добавлено и 12 удалено
  1. 21 12
      script.py
  2. 212 0
      tests/test_script_anti_ban.py

+ 21 - 12
script.py

@@ -323,6 +323,7 @@ class Script:
     def get_next_task(self) -> str:
         """
         获取下一个任务的名字, 大驼峰。
+        仅在当前任务执行结束后调用;防风控收尾在此处执行,不中断正在运行的任务。
         :return:
         """
         while True:
@@ -332,16 +333,17 @@ class Script:
                 self.state_queue.put({"schedule": self.config.get_schedule_data()})
             now = datetime.now()
             antiban_wake = self.anti_ban_guard.wake_time(now, self.config.script.anti_ban)
+            next_run = task.next_run
             if antiban_wake is not None:
-                task.next_run = max(task.next_run, antiban_wake)
+                next_run = max(next_run, antiban_wake)
             if not self._try_acquire_queue_token():
                 del_cached_property(self, "config")
                 continue
             # 任务时间到了返回任务名称
-            if task.next_run <= now:
+            if next_run <= now:
                 return task.command
             # 根据策略执行等待逻辑
-            if not self._handle_wait_during_idle(task.next_run):
+            if not self._handle_wait_during_idle(next_run, anti_ban=antiban_wake is not None):
                 # 若等待被打断, 则刷新配置
                 del_cached_property(self, "config")
 
@@ -397,13 +399,16 @@ class Script:
             if self.instance_guard.try_acquire():
                 return True
 
-    def _handle_wait_during_idle(self, next_run: datetime) -> bool:
+    def _handle_wait_during_idle(self, next_run: datetime, anti_ban: bool = False) -> bool:
         """
         处理任务空闲期间的行为策略
         :param next_run: 下一个任务的时间
+        :param anti_ban: 防风控休息时立即按所选策略收尾,不应用普通空闲的关闭阈值
         :return: True 表示等待成功完成, False 表示等待被中断
         """
         method = self.config.script.optimization.when_task_queue_empty
+        if anti_ban:
+            logger.info(f"Anti-ban rest until {next_run}, cleanup: {method}")
         strategy_map = {
             "close_game": self._wait_close_game,
             "goto_main": self._wait_goto_main,
@@ -411,8 +416,8 @@ class Script:
         func = strategy_map.get(method)
         if func is None:
             logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
-            func = self._wait_stay_there
-        return func(next_run)
+            return self._wait_stay_there(next_run)
+        return func(next_run, anti_ban=anti_ban)
 
     @staticmethod
     def _time_to_timedelta(value) -> timedelta:
@@ -448,8 +453,10 @@ class Script:
             return self.wait_until(next_run)
         return True
 
-    def _wait_close_game(self, next_run: datetime) -> bool:
+    def _wait_close_game(self, next_run: datetime, anti_ban: bool = False) -> bool:
         if self._emulator_down:
+            if anti_ban:
+                return self.wait_until(next_run)
             logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
             return self._wait_until_with_emulator_preheat(next_run)
 
@@ -458,7 +465,7 @@ class Script:
         close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
         close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
 
-        if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
+        if not anti_ban and close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
             logger.info("Close emulator during wait")
             self.device.emulator_stop()
             self._emulator_down = True
@@ -469,7 +476,7 @@ class Script:
             self.run("Restart")
             return True
 
-        if close_game_wait <= timedelta(0):
+        if anti_ban or close_game_wait <= timedelta(0):
             logger.info("Close game during wait")
             self.device.app_stop()
             self.device.release_during_wait()
@@ -493,14 +500,16 @@ class Script:
             return False
         return True
 
-    def _wait_goto_main(self, next_run: datetime) -> bool:
+    def _wait_goto_main(self, next_run: datetime, anti_ban: bool = False) -> bool:
         if self._emulator_down:
+            if anti_ban:
+                return self.wait_until(next_run)
             logger.info("Emulator is down, skip goto_main and wait with preheat")
             return self._wait_until_with_emulator_preheat(next_run)
 
         close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
         close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
-        if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
+        if not anti_ban and close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
             logger.info("Close emulator during wait")
             self.device.emulator_stop()
             self._emulator_down = True
@@ -680,7 +689,7 @@ class Script:
             #     logger.info('Server or network is recovered. Restart game client')
             #     self.config.task_call('Restart')
 
-            # Get task
+            # 上一轮 self.run() 已返回,才检查防风控并调度下一个任务。
             task = self.get_next_task()
             # Skip first restart
             if self.is_first_task and task == 'Restart':

+ 212 - 0
tests/test_script_anti_ban.py

@@ -0,0 +1,212 @@
+from datetime import datetime, time, timedelta
+from types import SimpleNamespace
+from unittest.mock import Mock, call
+
+import pytest
+
+import script as script_module
+from module.config import anti_ban as anti_ban_module
+from tasks.Script.config_antiban import AntiBan
+from tasks.Script.config_optimization import Optimization, WhenTaskQueueEmpty
+
+
+@pytest.fixture
+def scheduler(monkeypatch):
+    clock = SimpleNamespace(now=datetime(2026, 10, 23, 3))
+
+    class Clock(datetime):
+        @classmethod
+        def now(cls):
+            return clock.now
+
+    monkeypatch.setattr(script_module, 'datetime', Clock)
+    monkeypatch.setattr(anti_ban_module, 'datetime', Clock)
+    task = SimpleNamespace(command='Exploration', next_run=clock.now - timedelta(minutes=1))
+    script = object.__new__(script_module.Script)
+    script._emulator_down = False
+    script.instance_guard = None
+    script.state_queue = None
+    script.anti_ban_guard = anti_ban_module.AntiBanGuard()
+    script.config = SimpleNamespace(
+        script=SimpleNamespace(
+            anti_ban=AntiBan(enable=True),
+            optimization=Optimization(
+                close_game_wait_duration=time(12),
+                close_emulator_wait_duration=time(0, 1),
+            ),
+        ),
+        get_next=Mock(return_value=task),
+    )
+    script._try_acquire_queue_token = Mock(return_value=True)
+    script.device = Mock()
+    script.run = Mock(return_value=True)
+    script._wait_until_with_emulator_preheat = Mock(return_value=True)
+
+    def finish_wait(future):
+        clock.now = future + timedelta(seconds=1)
+        return True
+
+    script.wait_until = Mock(side_effect=finish_wait)
+    events = Mock()
+    events.attach_mock(script.device.app_stop, 'close_game')
+    events.attach_mock(script.device.emulator_stop, 'close_emulator')
+    events.attach_mock(script.device.release_during_wait, 'release')
+    events.attach_mock(script.run, 'run')
+    events.attach_mock(script.wait_until, 'wait')
+    return script, clock, task, events
+
+
+@pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
+@pytest.mark.parametrize('trigger', ['sleep_window', 'active_limit'])
+def test_anti_ban_finishes_using_selected_action_before_waiting(scheduler, method, trigger):
+    script, clock, task, events = scheduler
+    script.config.script.optimization.when_task_queue_empty = method
+    original_next_run = task.next_run
+    if trigger == 'active_limit':
+        config = script.config.script.anti_ban
+        config.sleep_start = config.sleep_end = time(0)
+        config.daily_active_limit = timedelta(hours=1)
+        config.long_rest_duration = timedelta(minutes=5)
+        script.anti_ban_guard.record_active(3600)
+        wake = clock.now + config.long_rest_duration
+    else:
+        wake = clock.now.replace(hour=8)
+
+    assert script.get_next_task() == 'Exploration'
+
+    # Both ordinary idle thresholds would change the requested action:
+    # the game-close threshold is longer than the rest, the emulator threshold shorter.
+    if method == WhenTaskQueueEmpty.CLOSE_GAME:
+        assert events.mock_calls == [
+            call.close_game(), call.release(), call.wait(wake), call.run('Restart'),
+        ]
+    else:
+        assert events.mock_calls == [
+            call.run('GotoMain'), call.release(), call.wait(wake),
+        ]
+    assert script.config.get_next.call_count == 2
+    assert task.next_run == original_next_run
+    script._wait_until_with_emulator_preheat.assert_not_called()
+
+
+@pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
+@pytest.mark.parametrize('trigger', ['sleep_window', 'active_limit'])
+def test_anti_ban_waits_for_running_task_to_finish(scheduler, monkeypatch, method, trigger):
+    script, clock, task, events = scheduler
+    clock.now = datetime(2026, 10, 23, 1, 59, 30)
+    task.next_run = clock.now - timedelta(minutes=1)
+    script.config_name = 'anti_ban_test'
+    script.is_first_task = False
+    script.failure_record = {}
+    script.config.model = SimpleNamespace(running_task='')
+    script.config.script.device = SimpleNamespace(run_background_only=True)
+    script.config.script.optimization.when_task_queue_empty = method
+    script.device.is_desktop = False
+    if trigger == 'active_limit':
+        config = script.config.script.anti_ban
+        config.sleep_start = config.sleep_end = time(0)
+        config.daily_active_limit = timedelta(minutes=1)
+        config.long_rest_duration = timedelta(minutes=5)
+    check_anti_ban = Mock(wraps=script.anti_ban_guard.wake_time)
+    monkeypatch.setattr(script.anti_ban_guard, 'wake_time', check_anti_ban)
+    monkeypatch.setattr(script_module.logger, 'set_file_logger', Mock())
+    monkeypatch.setattr(script_module, 'del_cached_property', Mock())
+    task_finished = False
+
+    def run(command):
+        nonlocal task_finished
+        if command == 'Exploration':
+            assert script.config.model.running_task == 'Exploration'
+            # Cross the sleep start / active limit while the same task is still running.
+            clock.now += timedelta(minutes=1)
+            assert check_anti_ban.call_count == 1
+            assert events.mock_calls == [call.run('Exploration')]
+            clock.now += timedelta(minutes=1)
+            task_finished = True
+            events.task_complete()
+        else:
+            assert command == 'GotoMain'
+            assert task_finished
+        return True
+
+    class RestStarted(Exception):
+        pass
+
+    def wait(future):
+        assert task_finished
+        assert script.config.model.running_task == ''
+        assert check_anti_ban.call_count == 2
+        raise RestStarted
+
+    script.run.side_effect = run
+    script.wait_until.side_effect = wait
+
+    with pytest.raises(RestStarted):
+        script.loop()
+
+    wake = (clock.now + timedelta(minutes=5) if trigger == 'active_limit'
+            else clock.now.replace(hour=8, minute=0, second=0))
+    cleanup = call.close_game() if method == WhenTaskQueueEmpty.CLOSE_GAME else call.run('GotoMain')
+    assert events.mock_calls == [
+        call.run('Exploration'), call.task_complete(), cleanup, call.release(), call.wait(wake),
+    ]
+
+
+@pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
+def test_disabling_anti_ban_during_wait_reloads_without_delaying_pending_task(
+        scheduler, monkeypatch, method):
+    script, clock, task, events = scheduler
+    script.config.script.optimization.when_task_queue_empty = method
+    original_next_run = task.next_run
+    script.wait_until.side_effect = None
+    script.wait_until.return_value = False
+
+    def reload_config(instance, name):
+        assert instance is script
+        assert name == 'config'
+        script.config.script.anti_ban.enable = False
+
+    reload = Mock(side_effect=reload_config)
+    monkeypatch.setattr(script_module, 'del_cached_property', reload)
+
+    assert script.get_next_task() == 'Exploration'
+
+    reload.assert_called_once_with(script, 'config')
+    script.wait_until.assert_called_once_with(clock.now.replace(hour=8))
+    assert task.next_run == original_next_run
+    assert call.run('Restart') not in events.mock_calls
+
+
+@pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
+def test_anti_ban_keeps_stopped_emulator_off_without_preheating(scheduler, method):
+    script, clock, task, events = scheduler
+    script.config.script.optimization.when_task_queue_empty = method
+    script._emulator_down = True
+
+    assert script.get_next_task() == 'Exploration'
+
+    assert events.mock_calls == [call.wait(datetime(2026, 10, 23, 8))]
+    script._wait_until_with_emulator_preheat.assert_not_called()
+    assert script._emulator_down is True
+
+
+def test_ordinary_short_idle_keeps_game_open_below_close_threshold(scheduler):
+    script, clock, task, events = scheduler
+    script.config.script.optimization.when_task_queue_empty = WhenTaskQueueEmpty.CLOSE_GAME
+    next_run = clock.now + timedelta(seconds=30)
+
+    assert script._handle_wait_during_idle(next_run) is True
+
+    assert events.mock_calls == [call.release(), call.wait(next_run)]
+
+
+@pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
+def test_ordinary_long_idle_still_closes_emulator_at_configured_threshold(scheduler, method):
+    script, clock, task, events = scheduler
+    script.config.script.optimization.when_task_queue_empty = method
+    next_run = clock.now + timedelta(minutes=5)
+
+    assert script._handle_wait_during_idle(next_run) is True
+
+    assert events.mock_calls == [call.close_emulator(), call.run('Restart')]
+    script._wait_until_with_emulator_preheat.assert_called_once_with(next_run)