booker_builtin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import os
  2. import time
  3. import json
  4. import threading
  5. import random
  6. import traceback
  7. import redis
  8. from typing import List, Dict, Callable
  9. from vs_types import GroupConfig, VSPlgConfig, Task, VSQueryResult, AppointmentType
  10. from vs_plg_factory import VSPlgFactory
  11. from toolkit.thread_pool import ThreadPool
  12. from toolkit.vs_cloud_api import VSCloudApi
  13. from toolkit.backoff import ExponentialBackoff
  14. class BuiltinBookerGCO:
  15. """
  16. 非绑定模式 (公共内置账号池):
  17. - 只维护全局 target_instances 数量的实例。
  18. - 所有实例热机等待,发现信号后临时去云端 Pop 订单。
  19. """
  20. def __init__(self, cfg: GroupConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  21. self.m_cfg = cfg
  22. self.m_factory = VSPlgFactory()
  23. self.m_logger = logger
  24. self.m_tasks: List[Task] = []
  25. self.m_lock = threading.RLock()
  26. self.m_stop_event = threading.Event()
  27. self.redis_client = redis.Redis(**redis_conf)
  28. self.m_pending_builtin = 0
  29. self.m_tracker_key = f"vs:worker:tasks_tracker:{self.m_cfg.identifier}"
  30. self.group_backoff = ExponentialBackoff(base_delay=60.0, max_delay=10*60.0, factor=2.0)
  31. self.task_backoff = ExponentialBackoff(base_delay=5*60.0, max_delay=2*60*60.0, factor=2.0)
  32. self.m_last_spawn_time = 0.0
  33. self.heartbeat_ttl = 300
  34. def _log(self, message):
  35. if self.m_logger:
  36. self.m_logger(f'[BUILTIN-BOOKER] [{self.m_cfg.identifier}] {message}')
  37. def start(self):
  38. if not self.m_cfg.enable:
  39. return
  40. self._log("Starting Built-in Booker...")
  41. plugin_name = self.m_cfg.plugin_config.plugin_name
  42. class_name = "".join(part.title() for part in plugin_name.split('_'))
  43. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  44. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  45. threading.Thread(target=self._booking_trigger_loop, daemon=True).start()
  46. threading.Thread(target=self._creator_loop, daemon=True).start()
  47. threading.Thread(target=self._maintain_loop, daemon=True).start()
  48. def stop(self):
  49. self._log("Stopping Booker...")
  50. self.m_stop_event.set()
  51. def _get_redis_key(self, routing_key: str) -> str:
  52. return f"vs:signal:{routing_key}"
  53. def _maintain_loop(self):
  54. self._log("Maintain loop started.")
  55. while not self.m_stop_event.is_set():
  56. time.sleep(1.0)
  57. now = time.time()
  58. with self.m_lock:
  59. tasks_to_check = list(self.m_tasks)
  60. if not tasks_to_check:
  61. continue
  62. healthy_tasks = []
  63. for t in tasks_to_check:
  64. if now >= t.next_remote_ping:
  65. try:
  66. t.instance.keep_alive()
  67. if t.instance.health_check():
  68. healthy_tasks.append(t)
  69. next_delay = random.randint(180, 300)
  70. t.next_remote_ping = now + next_delay
  71. else:
  72. self._log(f"♻️ Instance unhealthy. Will be removed.")
  73. except Exception as e:
  74. self._log(f"Instance keep-alive failed: {e}")
  75. else:
  76. healthy_tasks.append(t)
  77. with self.m_lock:
  78. self.m_tasks = [t for t in self.m_tasks if t in healthy_tasks]
  79. def _booking_trigger_loop(self):
  80. self._log("Trigger loop started.")
  81. while not self.m_stop_event.is_set():
  82. try:
  83. time.sleep(1.0)
  84. now = time.time()
  85. for apt_type in self.m_cfg.appointment_types:
  86. redis_key = self._get_redis_key(apt_type.routing_key)
  87. raw_data = self.redis_client.get(redis_key)
  88. if not raw_data:
  89. continue
  90. try:
  91. data = json.loads(raw_data)
  92. query_result = VSQueryResult.model_validate(data['query_result'])
  93. query_result.apt_type = AppointmentType.model_validate(data['apt_type'])
  94. except Exception as parse_err:
  95. self._log(f"Data parsing error for {redis_key}: {parse_err}. Deleting corrupted signal.")
  96. self.redis_client.delete(redis_key)
  97. continue
  98. matching_tasks = []
  99. with self.m_lock:
  100. for task in self.m_tasks:
  101. if now < task.next_run or not task.book_allowed:
  102. continue
  103. if apt_type.routing_key not in task.acceptable_routing_keys:
  104. continue
  105. self._log(f"🚀 Triggering BOOK for {apt_type.routing_key}")
  106. task.next_run = now + self.m_cfg.booker.booking_cooldown
  107. matching_tasks.append(task)
  108. if matching_tasks:
  109. threads = []
  110. for task in matching_tasks:
  111. self._log(f"🚀 Triggering BOOK for {apt_type.routing_key}")
  112. t = threading.Thread(target=self._execute_book_job, args=(task, query_result))
  113. threads.append(t)
  114. t.start()
  115. for t in threads:
  116. t.join()
  117. except Exception as e:
  118. self._log(f"Trigger loop error: {e}")
  119. time.sleep(2)
  120. def _execute_book_job(self, task: Task, query_result: VSQueryResult):
  121. queue_name = f"auto.{query_result.apt_type.routing_key}"
  122. task_id = None
  123. task_data = None
  124. booking_success = False
  125. is_rate_limited = False
  126. try:
  127. task_data = VSCloudApi.Instance().get_vas_task_pop(queue_name)
  128. if not task_data:
  129. return
  130. task_id = task_data['id']
  131. order_id = task_data.get('order_id')
  132. self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + self.heartbeat_ttl})
  133. user_input = task_data.get('user_inputs', {})
  134. book_res = task.instance.book(query_result, user_input)
  135. if book_res.success:
  136. booking_success = True
  137. self._log(f"✅ BOOK SUCCESS! Order: {order_id}")
  138. grab_info = {
  139. "account": book_res.account,
  140. "session_id": book_res.session_id,
  141. "urn": book_res.urn,
  142. "slot_date": book_res.book_date,
  143. "slot_time": book_res.book_time,
  144. "timestamp": int(time.time()),
  145. "payment_link": book_res.payment_link
  146. }
  147. VSCloudApi.Instance().update_vas_task(task_id, {"status": "grabbed", "grabbed_history": grab_info})
  148. push_content = (
  149. f"🎉 【预定成功通知】\n"
  150. f"━━━━━━━━━━━━━━━\n"
  151. f"订单编号: {order_id}\n"
  152. f"预约账号: {book_res.account}\n"
  153. f"预约日期: {book_res.book_date}\n"
  154. f"预约时间: {book_res.book_time}\n"
  155. f"预约编号: {book_res.urn}\n"
  156. f"支付链接: {book_res.payment_link if book_res.payment_link else '无需支付/暂无'}\n"
  157. f"━━━━━━━━━━━━━━━\n"
  158. )
  159. VSCloudApi.Instance().push_weixin_text(push_content)
  160. self.redis_client.zrem(self.m_tracker_key, task_id)
  161. # === 核心:成功次数判断 ===
  162. task.successful_bookings += 1
  163. max_b = self.m_cfg.booker.max_bookings_per_account
  164. if max_b > 0 and task.successful_bookings >= max_b:
  165. self._log(f"Account reached max bookings ({max_b}). Destroying instance.")
  166. with self.m_lock:
  167. if task in self.m_tasks:
  168. self.m_tasks.remove(task)
  169. else:
  170. self._log(f"❌ BOOK FAILED for Order: {order_id}")
  171. except Exception as e:
  172. err_str = str(e)
  173. self._log(f"Exception during booking: {err_str}")
  174. rate_limited_indicators = [
  175. "42901" in err_str,
  176. "Rate limited" in err_str
  177. ]
  178. if any(rate_limited_indicators):
  179. is_rate_limited = True
  180. with self.m_lock:
  181. if task in self.m_tasks:
  182. self.m_tasks.remove(task)
  183. if task_data and task_id is not None:
  184. task_meta = task_data.get('meta') or {}
  185. t_fails = task_meta.get('booking_failures', 0) + 1
  186. task_meta['booking_failures'] = t_fails
  187. try:
  188. VSCloudApi.Instance().update_vas_task(task_id, {"meta": task_meta})
  189. except Exception as cloud_err:
  190. self._log(f"Failed to update task meta: {cloud_err}")
  191. t_cd = self.task_backoff.calculate(t_fails)
  192. self._log(f"⏳ Task={task_id} (Booking Attempt {t_fails}) suspended for {t_cd:.1f}s.")
  193. def delayed_return(tid, wait_sec, reason):
  194. self.m_stop_event.wait(wait_sec)
  195. self._safe_return_task(tid, reason=reason)
  196. self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + t_cd})
  197. finally:
  198. if not booking_success and task_id is not None and not is_rate_limited:
  199. self.redis_client.zadd(self.m_tracker_key, {str(task_id): 0})
  200. self._log(f"♻️ Task={task_id} normal failure. Instantly handed over to Sweeper.")
  201. def _creator_loop(self):
  202. self._log("Creator loop started.")
  203. spawn_interval = 10.0
  204. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  205. while not self.m_stop_event.is_set():
  206. time.sleep(2.0)
  207. if self.redis_client.exists(group_cd_key):
  208. continue
  209. with self.m_lock:
  210. current = len(self.m_tasks)
  211. pending = self.m_pending_builtin
  212. target = self.m_cfg.booker.target_instances
  213. if (current + pending) < target:
  214. now = time.time()
  215. if now - self.m_last_spawn_time >= spawn_interval:
  216. self.m_last_spawn_time = now
  217. self._spawn_worker()
  218. def _spawn_worker(self):
  219. with self.m_lock:
  220. self.m_pending_builtin += 1
  221. def _job():
  222. try:
  223. plg_cfg = VSPlgConfig()
  224. plg_cfg.debug = self.m_cfg.debug
  225. plg_cfg.free_config = self.m_cfg.free_config
  226. plg_cfg.session_max_life = self.m_cfg.session_max_life
  227. if self.m_cfg.need_account:
  228. acc = VSCloudApi.Instance().get_next_account(self.m_cfg.booker.account_pool_id, self.m_cfg.booker.account_cd)
  229. plg_cfg.account.id = acc['id']
  230. plg_cfg.account.username = acc['username']
  231. plg_cfg.account.password = acc['password']
  232. if self.m_cfg.need_proxy:
  233. proxy = VSCloudApi.Instance().get_next_proxy(self.m_cfg.proxy_pool, self.m_cfg.proxy_cd)
  234. plg_cfg.proxy.id = proxy['id']
  235. plg_cfg.proxy.ip = proxy['ip']
  236. plg_cfg.proxy.port = proxy['port']
  237. plg_cfg.proxy.proto = proxy['proto']
  238. plg_cfg.proxy.username = proxy['username']
  239. plg_cfg.proxy.password = proxy['password']
  240. instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
  241. instance.set_log(self.m_logger)
  242. instance.set_config(plg_cfg)
  243. instance.create_session()
  244. with self.m_lock:
  245. all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
  246. self.m_tasks.append(
  247. Task(
  248. instance=instance,
  249. qw_cfg=self.m_cfg.query_wait,
  250. next_run=time.time(),
  251. task_ref=None,
  252. acceptable_routing_keys=all_keys,
  253. source_queue="built-in",
  254. book_allowed=True,
  255. next_remote_ping = time.time() + random.randint(180, 300)
  256. )
  257. )
  258. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  259. self.redis_client.delete(group_fail_key)
  260. self._log(f"+++ Built-in Booker spawned: {plg_cfg.account.username}")
  261. except Exception as e:
  262. err_str = str(e)
  263. resource_not_found_indicators = [
  264. "40401" in err_str,
  265. "Account not found" in err_str,
  266. "Proxy not found" in err_str,
  267. ]
  268. if any(resource_not_found_indicators):
  269. return
  270. self._log(f"Spawn failed: {e}")
  271. rate_limited_indicators = [
  272. "42901" in err_str,
  273. "Rate limited" in err_str
  274. ]
  275. if any(rate_limited_indicators):
  276. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  277. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  278. # 更新全局(机器组)失败次数
  279. g_fails = self.redis_client.incr(group_fail_key)
  280. # 计算退避时间
  281. g_cd = self.group_backoff.calculate(g_fails)
  282. # 设置 Redis 全局冷却保护阀
  283. self.redis_client.set(group_cd_key, "1", ex=int(g_cd))
  284. self._log(f"📉 [Rate Limited] Group '{self.m_cfg.identifier}' failed {g_fails} times. Global Backoff: {g_cd:.1f}s.")
  285. finally:
  286. with self.m_lock:
  287. self.m_pending_builtin = max(0, self.m_pending_builtin - 1)
  288. ThreadPool.getInstance().enqueue(_job)