"""Desktop scheduling semantics without Qt timers or concurrent Engine access.""" from __future__ import annotations import math import random import threading import time FAST_KINDS = ("hatch", "gift", "explore", "breakthrough") class AccountSchedule: """Deadlines belong to one worker and are inspected only on its thread.""" def __init__(self, *, clock=time.monotonic, uniform=random.uniform): self.clock, self.uniform = clock, uniform self.next_poll = math.inf self.next_fast = {kind: math.inf for kind in FAST_KINDS} self.monitoring = False self.last_maintenance_error = {} self.game_paused = False self.retry_deadline = None self.retry_attempt = 0 def game_failed(self, *, retry=False): self.game_paused = True self.stop() self.retry_deadline = None if retry: self.retry_attempt += 1 delay = min(5 * 2 ** min(self.retry_attempt - 1, 4), 60) self.retry_deadline = self.clock() + delay return delay def game_resumed(self): self.game_paused = False self.retry_deadline = None self.retry_attempt = 0 def monitor(self, enabled=True): self.monitoring = bool(enabled) self.next_poll = self.clock() if enabled else math.inf def stop(self): for kind in FAST_KINDS: self.next_fast[kind] = math.inf def poll_finished(self, config): self.next_poll = self.clock() + self.uniform(0, config.get("interval", 30)) def maintenance_failed(self, kind): self.last_maintenance_error[kind] = self.clock() def arm(self, engine, config, running, plans=(), *, completed=None): if completed in self.next_fast: self.next_fast[completed] = math.inf snapshot = engine.snapshot if not self.monitoring or not running or snapshot is None: self.stop() return now = self.clock() policy = config.get("policy", {}) pending = bool(engine._progression_pending() or engine.explore_planner.pending(snapshot) or engine._breakthrough_pending) delays = {} if not pending: if policy.get("enabled") and policy.get("fill") and engine.pending_hatches: delays["hatch"] = self.uniform(1, 2) ready_at = engine.gift_planner.next_ready_at if policy.get("gift_enabled") and ready_at is not None: delays["gift"] = max(0, ready_at - snapshot.now) if any(action.path and (action.kind == "explore_finish" or action.kind == "explore_start" and config.get("explore_policy", {}).get("enabled")) for action in plans): delays["explore"] = 1.0 for team in snapshot.raw.get("exploreTeams") or []: if isinstance(team, dict) and team.get("status") in (1, "1"): remaining = engine.explore_planner.remaining(snapshot, team) if remaining is not None: delays["explore"] = min(delays.get("explore", math.inf), max(1.0, remaining + 1)) if policy.get("breakthrough_targets") and any(action.path and action.kind in ("potential", "breakthrough") for action in plans): delays["breakthrough"] = 1.0 for kind in FAST_KINDS: if kind not in delays: self.next_fast[kind] = math.inf elif self.next_fast[kind] == math.inf: self.next_fast[kind] = now + delays[kind] def due(self, engine, config, running): now = self.clock() if self.game_paused: return "retry" if self.retry_deadline is not None and now >= self.retry_deadline else None def allowed(kind): return now - self.last_maintenance_error.get(kind, -math.inf) >= 30 connected = not engine.demo and engine.client is not None and engine.snapshot is not None if connected and engine.heartbeat_enabled and now - engine.last_heartbeat >= 240 and allowed("heartbeat"): return "heartbeat" if connected and self.monitoring and engine.pending_recovery_due() and allowed("reconcile"): return "reconcile" if connected and engine.heartbeat_enabled and engine.master_sync_due() and allowed("master_sync"): return "master_sync" if connected and engine.heartbeat_enabled and engine.growth_sync_due() and allowed("growth_sync"): return "growth_sync" if self.monitoring and running and now >= self.next_fast["hatch"]: return "hatch" if self.monitoring and now >= self.next_poll: return "poll" if self.monitoring and running: for kind in ("gift", "explore", "breakthrough"): if now >= self.next_fast[kind]: return kind return None class Scheduler: """Ask idle account queues to tick; never call an Engine from this thread.""" def __init__(self, workers, *, interval=0.2): self.workers = workers self.interval = interval self.closed = threading.Event() self.thread = threading.Thread(target=self._run, name="ranch-web-scheduler", daemon=True) self.thread.start() def _run(self): while not self.closed.wait(self.interval): for worker in self.workers(): worker.request_tick() def close(self): self.closed.set() if threading.current_thread() is not self.thread: self.thread.join(timeout=2)