import os import time import random import threading from datetime import datetime from typing import Dict, Callable, Optional from core_types import ( BookerStandaloneConfig, QueryWaitMode, PluginConfig, QueryResult, BookResult, GroupStatus, PluginStatus, utc_now_str, BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError, NetworkTimeoutError ) from plugin_factory import PluginFactory from utils.safe_redis_cli import SafeRedisClient from toolkit.proxy_manager import ProxyManager from toolkit.cloud_api import CloudApi from toolkit.notifier import notify_date_changes, notify_book_result class StandaloneGCO: """ Standalone GCO 实例管理器。 遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。 """ TAG = "STANDALONE" def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None): self.m_cfg = cfg self.m_logger = logger self.m_factory = PluginFactory() self.m_instance = None self.m_lock = threading.RLock() self.m_stop_event = threading.Event() self.m_last_login_time = 0 self.m_next_query_time = 0 self.m_next_keepalive_time = 0 self.m_last_wait_log_time = 0.0 self.m_current_dates = {} self.redis_client = SafeRedisClient(redis_conf, self.m_logger) def _log(self, message: str): prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]" if self.m_logger: self.m_logger(f"{prefix} {message}") else: print(f"{prefix} {message}") def _get_wait_interval(self) -> float: """根据配置计算下一次查询的等待时间""" mode = self.m_cfg.query_wait.mode if mode == QueryWaitMode.Loop: return 1.0 elif mode == QueryWaitMode.Fixed: return float(self.m_cfg.query_wait.fixed_wait) elif mode == QueryWaitMode.Random: return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max) return 30.0 def _is_within_active_hours(self) -> bool: """判断当前是否在允许创建实例和查询的时间段内""" start_str = self.m_cfg.active_time_start end_str = self.m_cfg.active_time_end current_bj_time = datetime.utcnow().time() start_time = datetime.strptime(start_str, "%H:%M").time() end_time = datetime.strptime(end_str, "%H:%M").time() return start_time <= current_bj_time <= end_time def update_config(self, new_cfg: BookerStandaloneConfig): """动态更新配置""" with self.m_lock: if self.m_cfg.enable and not new_cfg.enable: self._log("Config dynamically updated: Group DISABLED.") elif not self.m_cfg.enable and new_cfg.enable: self._log("Config dynamically updated: Group ENABLED.") else: self._log("Config dynamically updated: Parameters refreshed.") self.m_cfg = new_cfg def get_status(self) -> GroupStatus: with self.m_lock: instance = self.m_instance gid = self.m_cfg.identifier enable = self.m_cfg.enable plugin_name = self.m_cfg.plugin_config.plugin_name plugins_status = [] healthy_count = 0 if instance: st = instance.get_plugin_status() if st.is_healthy: healthy_count += 1 plugins_status.append(st) return GroupStatus( group_id=gid, enable=enable, plugin_name=plugin_name, total_tasks=1 if instance else 0, healthy_tasks=healthy_count, plugins=plugins_status, updated_at=utc_now_str(), ) def start(self): """非阻塞启动,注册插件并开启后台工作线程""" if not self.m_cfg.enable: return self._log("Starting Standalone GCO...") plugin_name = self.m_cfg.plugin_config.plugin_name class_name = "".join(part.title() for part in plugin_name.split('_')) plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin) self.m_factory.register_plugin(plugin_name, plugin_path, class_name) worker_name = f"Standalone-{self.m_cfg.identifier}" threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start() def stop(self): """优雅停止""" self._log("Stopping Standalone GCO...") self.m_stop_event.set() self._cleanup_instance("standalone stopped") def _cleanup_instance(self, reason: str = ""): with self.m_lock: if self.m_instance is not None: try: self._log(f"🧹 Cleaned up instance. Reason: {reason}") self.m_instance.cleanup() except Exception as e: self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}") finally: self.m_instance = None def _init_instance(self): """初始化单实例并进行登录创建会话""" self._cleanup_instance("recreating new session") now = time.time() if now < self.m_last_login_time + self.m_cfg.login_interval: wait_time = self.m_last_login_time + self.m_cfg.login_interval - now self._log(f"Waiting {int(wait_time)}s for login interval cooldown...") if self.m_stop_event.wait(wait_time): return plugin_name = self.m_cfg.plugin_config.plugin_name plg_cfg = PluginConfig() plg_cfg.debug = self.m_cfg.debug plg_cfg.account = self.m_cfg.account proxy = ProxyManager.Instance().get_next_proxy(self.m_cfg.proxy_pool, proxy_cd=600) plg_cfg.proxy = type(plg_cfg.proxy)(**proxy) plg_cfg.free_config = self.m_cfg.free_config plg_cfg.session_max_life = self.m_cfg.session_max_life instance = self.m_factory.create(self.m_cfg.identifier, plugin_name) instance.set_log(self.m_logger) instance.set_config(plg_cfg) with self.m_lock: self.m_instance = instance self._log("Creating session...") instance.create_session() self.m_last_login_time = time.time() interval = self._get_wait_interval() self.m_next_query_time = time.time() + interval self.m_next_keepalive_time = time.time() + 10.0 self._log(f"Session created successfully. Initial query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')}).") def _normalize_error(self, err: Exception) -> BizException: """ 将任意异常规整化为领域异常 BizException。 保留对未结构化历史异常字符串特征的兜底兼容识别。 """ if isinstance(err, BizException): return err err_str = str(err) if "42901" in err_str or "Rate limited" in err_str: return RateLimiteddError(message=err_str) if "40101" in err_str or "Session expired" in err_str or "session invalid" in err_str.lower(): return SessionExpiredOrInvalidError(message=err_str) if "40301" in err_str or "403" in err_str or "Cloudflare Access Denied" in err_str: return PermissionDeniedError(message=err_str) return BizException( code=50000, message=f"Unhandled ({type(err).__name__}): {err_str}", ) def _dispatch_error_policy(self, action: str, err: Exception) -> None: """ Standalone 错误调度与自愈策略引擎 (Policy Engine): 基于 (Action, 异常事实类型) 矩阵 + Standalone 单机模式 + 本组配置闭环执行自愈动作: - create_session/login 时 429:判定为账号级限流,锁定账号,执行 login_interval 退避等待; - query 时 429:会话已建立,判定为出口 IP 频率超限,不锁定账号,销毁实例触发下轮代理轮换; - session expired / 401:销毁当前实例,重置下一次查询时间为 5s 后以触发重新登录; - 403 Forbidden / WAF:判定为 IP 被封,清理实例换 IP 并退避; - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。 """ biz_err = self._normalize_error(err) acc = self.m_cfg.account if (self.m_cfg.account and self.m_cfg.account.username not in ("", "Guest")) else None # 1. 目标站限流 / 429 if isinstance(biz_err, RateLimiteddError): if action in ("create_session", "login", "spawn"): backoff = float(self.m_cfg.login_interval) self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).") if acc and getattr(acc, "id", 0): try: CloudApi.Instance().lock_account(acc.id, int(backoff)) self._log(f"🔒 Account [{acc.username}] locked for {int(backoff)}s via Cloud API.") except Exception as lock_err: self._log(f"Failed to lock account via cloud API: {lock_err}") self.m_last_login_time = time.time() self._cleanup_instance(f"{action} account rate limited") elif action == "query": # 查询时 429:出口 IP 限流,绝不锁账号,换 IP 即可! self._log("🔄 [Proxy Rate Limited] Query hit 429 (IP throttled, Account preserved). Cleaning instance to rotate proxy...") self._cleanup_instance("query ip rate limited") self.m_next_query_time = time.time() + 10.0 else: self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.") self.m_next_query_time = time.time() + 10.0 # 2. 会话过期 / 401 elif isinstance(biz_err, SessionExpiredOrInvalidError): if action in ("create_session", "login", "spawn"): self._log(f"❌ [Auth Failed] Session creation failed (401 invalid credentials or challenge). Backing off for 10s...") self.m_last_login_time = time.time() - self.m_cfg.login_interval + 10.0 self._cleanup_instance(f"{action} auth failed") else: self._log(f"🔄 [Session Expired] Session died during {action}. Cleaning up instance for re-login in 5s...") self._cleanup_instance(f"{action} session expired") self.m_next_query_time = time.time() + 5.0 # 3. 权限被拒 / WAF 拦截 / 403 elif isinstance(biz_err, PermissionDeniedError): self._log(f"🛡️ [WAF Blocked] 403 Forbidden detected during {action}. Cleaning instance to rotate proxy (60s cooldown)...") self._cleanup_instance(f"{action} waf blocked") self.m_next_query_time = time.time() + 60.0 # 4. 网络或浏览器超时 elif isinstance(biz_err, NetworkTimeoutError): self._log(f"⏱️ [Timeout] Network/browser timeout during {action}. Retrying in 5s...") self.m_next_query_time = time.time() + 5.0 # 5. 兜底策略 else: self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})") if action in ("create_session", "worker_loop"): self.m_last_login_time = time.time() - self.m_cfg.login_interval + 5.0 else: self.m_next_query_time = time.time() + 10.0 def _worker_loop(self): """ 后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定 """ self._log("Standalone worker loop started.") while not self.m_stop_event.is_set(): try: if not self.m_cfg.enable: self.m_stop_event.wait(1.0) continue if not self._is_within_active_hours(): self.m_stop_event.wait(5.0) continue # 1. 会话初始化与自愈 if self.m_instance is None: try: self._init_instance() except Exception as e: self._dispatch_error_policy("create_session", e) continue # 2. 健康检查 if self.m_instance and not self.m_instance.health_check(): self._log("Health check failed. Session dead. Recreating session...") self._cleanup_instance("session health check failed") continue # 3. 查询等待与周期性保活 now = time.time() if now < self.m_next_query_time: remaining = self.m_next_query_time - now next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S') keep_alive_sec = self.m_cfg.keep_alive # 周期性保活 if self.m_instance and now >= self.m_next_keepalive_time: self.m_instance.keep_alive() self.m_next_keepalive_time = now + keep_alive_sec self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...") self.m_last_wait_log_time = now # 周期性显示等待倒计时(每隔 15 秒提示一次) elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0: self.m_last_wait_log_time = now self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...") wait_sec = min(remaining, 1.0) self.m_stop_event.wait(wait_sec) continue # 4. 随机选取 routing_key 进行查询 apt_types = self.m_cfg.appointment_types if not apt_types: self.m_stop_event.wait(2.0) continue weights = [max(0.0, float(t.weight)) for t in apt_types] if sum(weights) > 0: apt_type = random.choices(apt_types, weights=weights, k=1)[0] else: apt_type = random.choice(apt_types) self._log(f"Querying slots for {apt_type.routing_key}...") try: query_result = self.m_instance.query(apt_type) query_result.apt_type = apt_type notify_date_changes(query_result, cache=self.m_current_dates, logger=self._log) except Exception as e: self._dispatch_error_policy("query", e) continue # 5. 发现档期,执行自动预定 if query_result.success: self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...") try: book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences) notify_book_result(book_result, logger=self._log) if book_result.success: self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!") self.m_stop_event.wait(5.0) except Exception as e: self._dispatch_error_policy("book", e) # 6. 在所有操作(包括抢单流程)执行完毕后,再统一计算并调度下一次查询时间与保活时间 interval = self._get_wait_interval() now = time.time() self.m_next_query_time = now + interval keep_alive_sec = self.m_cfg.keep_alive self.m_next_keepalive_time = now + keep_alive_sec self.m_last_wait_log_time = now self._log(f"Next query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')})...") except Exception as e: self._dispatch_error_policy("worker_loop", e)