booker_builtin.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import os
  2. import time
  3. import json
  4. import threading
  5. import random
  6. import redis
  7. from typing import List, Dict, Callable
  8. import configure
  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_com = redis.Redis(**redis_conf)
  28. self.redis_sub = redis.Redis(**redis_conf)
  29. self.m_pending_builtin = 0
  30. self.m_tracker_key = f"vs:worker:tasks_tracker:{self.m_cfg.identifier}"
  31. self.group_backoff = ExponentialBackoff(base_delay=60.0, max_delay=10*60.0, factor=2.0)
  32. self.task_backoff = ExponentialBackoff(base_delay=5*60.0, max_delay=2*60*60.0, factor=2.0)
  33. self.m_last_spawn_time = 0.0
  34. self.heartbeat_ttl = 300
  35. def _log(self, message):
  36. if self.m_logger:
  37. self.m_logger(f'[BUILTIN-BOOKER] [{self.m_cfg.identifier}] {message}')
  38. def start(self):
  39. if not self.m_cfg.enable:
  40. return
  41. self._log("Starting Built-in Booker...")
  42. plugin_name = self.m_cfg.plugin_config.plugin_name
  43. class_name = "".join(part.title() for part in plugin_name.split('_'))
  44. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  45. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  46. threading.Thread(target=self._booking_trigger_loop, daemon=True).start()
  47. threading.Thread(target=self._creator_loop, daemon=True).start()
  48. threading.Thread(target=self._maintain_loop, daemon=True).start()
  49. def stop(self):
  50. self._log("Stopping Booker...")
  51. self.m_stop_event.set()
  52. self._cleanup_all_tasks("booker stop")
  53. def _cleanup_task(self, task: Task, reason: str = ""):
  54. try:
  55. instance = getattr(task, 'instance', None)
  56. if instance and hasattr(instance, 'cleanup'):
  57. instance.cleanup()
  58. self._log(f"🧹 Cleaned up built-in instance. Reason: {reason}")
  59. except Exception as e:
  60. self._log(f"Cleanup failed for built-in instance. Reason: {reason}. Error: {e}")
  61. def _remove_task(self, task: Task, reason: str = "", cleanup: bool = True):
  62. removed = False
  63. with self.m_lock:
  64. if task in self.m_tasks:
  65. self.m_tasks.remove(task)
  66. removed = True
  67. if cleanup and removed:
  68. self._cleanup_task(task, reason)
  69. return removed
  70. def _cleanup_all_tasks(self, reason: str = ""):
  71. with self.m_lock:
  72. tasks = list(self.m_tasks)
  73. self.m_tasks.clear()
  74. for task in tasks:
  75. self._cleanup_task(task, reason)
  76. def _get_redis_key(self, routing_key: str) -> str:
  77. return f"vs:signal:{routing_key}"
  78. def _maintain_loop(self):
  79. self._log("Maintain loop started.")
  80. while not self.m_stop_event.is_set():
  81. time.sleep(1.0)
  82. now = time.time()
  83. with self.m_lock:
  84. tasks_to_check = list(self.m_tasks)
  85. if not tasks_to_check:
  86. continue
  87. healthy_tasks = []
  88. dead_tasks = []
  89. for t in tasks_to_check:
  90. if now >= t.next_remote_ping:
  91. try:
  92. t.instance.keep_alive()
  93. if t.instance.health_check():
  94. healthy_tasks.append(t)
  95. next_delay = random.randint(180, 300)
  96. t.next_remote_ping = now + next_delay
  97. else:
  98. dead_tasks.append(t)
  99. self._log(f"♻️ Instance unhealthy. Will be removed.")
  100. except Exception as e:
  101. dead_tasks.append(t)
  102. self._log(f"Instance keep-alive failed: {e}")
  103. else:
  104. healthy_tasks.append(t)
  105. if dead_tasks:
  106. with self.m_lock:
  107. current_tasks = list(self.m_tasks)
  108. self.m_tasks = [t for t in self.m_tasks if t in healthy_tasks]
  109. for t in dead_tasks:
  110. if t in current_tasks:
  111. self._cleanup_task(t, "unhealthy or keep-alive failed")
  112. else:
  113. with self.m_lock:
  114. self.m_tasks = [t for t in self.m_tasks if t in healthy_tasks]
  115. def _booking_trigger_loop(self):
  116. self._log("Pub/Sub Trigger loop started.")
  117. channel_to_routing_key = {}
  118. for apt in self.m_cfg.appointment_types:
  119. channel = self._get_redis_key(apt.routing_key)
  120. channel_to_routing_key[channel] = apt.routing_key
  121. if not channel_to_routing_key:
  122. self._log("No appointment types configured. Exiting trigger loop.")
  123. return
  124. pubsub = None
  125. while not self.m_stop_event.is_set():
  126. try:
  127. if pubsub is None:
  128. pubsub = self.redis_sub.pubsub(ignore_subscribe_messages=False)
  129. channels_to_sub = list(channel_to_routing_key.keys())
  130. self._log(f"⏳ Sending SUBSCRIBE command to Redis for: {channels_to_sub}")
  131. pubsub.subscribe(*channels_to_sub)
  132. message = pubsub.get_message(timeout=5.0)
  133. if not message:
  134. continue
  135. channel = message['channel']
  136. if isinstance(channel, bytes):
  137. channel = channel.decode('utf-8')
  138. if message['type'] == 'subscribe':
  139. active_subs = message['data']
  140. self._log(f"📡 [Redis ACK] Successfully subscribed to: {channel} (Active connection subs: {active_subs})")
  141. continue
  142. if message['type'] != 'message':
  143. continue
  144. raw_data = message['data']
  145. if isinstance(raw_data, bytes):
  146. raw_data = raw_data.decode('utf-8')
  147. routing_key = channel_to_routing_key.get(channel)
  148. if not routing_key:
  149. continue
  150. try:
  151. data = json.loads(raw_data)
  152. query_result = VSQueryResult.model_validate(data['query_result'])
  153. query_result.apt_type = AppointmentType.model_validate(data['apt_type'])
  154. except Exception as parse_err:
  155. self._log(f"Data parsing error for channel {channel}: {parse_err}")
  156. continue
  157. now = time.time()
  158. matching_tasks = []
  159. with self.m_lock:
  160. for task in self.m_tasks:
  161. if now < task.next_run or not task.book_allowed:
  162. continue
  163. if routing_key not in task.acceptable_routing_keys:
  164. continue
  165. task.next_run = now + self.m_cfg.booker.booking_cooldown
  166. matching_tasks.append(task)
  167. if matching_tasks:
  168. for task in matching_tasks:
  169. self._log(f"🚀 Triggering BOOK for {routing_key} | Order Ref: {task.task_ref}")
  170. t = threading.Thread(
  171. target=self._execute_book_job,
  172. args=(task, query_result),
  173. daemon=True
  174. )
  175. t.start()
  176. except Exception as e:
  177. self._log(f"Trigger loop pub/sub error: {e}")
  178. if pubsub:
  179. try:
  180. pubsub.close()
  181. except:
  182. pass
  183. pubsub = None
  184. time.sleep(2)
  185. if pubsub:
  186. pubsub.close()
  187. self._log("Pub/Sub connection closed.")
  188. def _execute_book_job(self, task: Task, query_result: VSQueryResult):
  189. queue_name = f"auto.{query_result.apt_type.routing_key}"
  190. task_id = None
  191. task_data = None
  192. booking_success = False
  193. is_rate_limited = False
  194. try:
  195. task_data = VSCloudApi.Instance().get_vas_task_pop(queue_name)
  196. if not task_data:
  197. return
  198. task_id = task_data['id']
  199. order_id = task_data.get('order_id')
  200. self.redis_com.zadd(self.m_tracker_key, {str(task_id): time.time() + self.heartbeat_ttl})
  201. user_input = task_data.get('user_inputs', {})
  202. book_res = task.instance.book(query_result, user_input)
  203. if book_res.success:
  204. booking_success = True
  205. self._log(f"✅ BOOK SUCCESS! Order: {order_id}")
  206. grab_info = {
  207. "account": book_res.account,
  208. "session_id": book_res.session_id,
  209. "urn": book_res.urn,
  210. "slot_date": book_res.book_date,
  211. "slot_time": book_res.book_time,
  212. "timestamp": int(time.time()),
  213. "payment_link": book_res.payment_link
  214. }
  215. VSCloudApi.Instance().update_vas_task(task_id, {"status": "grabbed", "grabbed_history": grab_info})
  216. push_content = (
  217. f"🎉 【预定成功通知】\n"
  218. f"━━━━━━━━━━━━━━━\n"
  219. f"订单编号: {order_id}\n"
  220. f"预约账号: {book_res.account}\n"
  221. f"预约日期: {book_res.book_date}\n"
  222. f"预约时间: {book_res.book_time}\n"
  223. f"预约编号: {book_res.urn}\n"
  224. f"支付链接: {book_res.payment_link if book_res.payment_link else '无需支付/暂无'}\n"
  225. f"━━━━━━━━━━━━━━━\n"
  226. )
  227. VSCloudApi.Instance().push_weixin_text(push_content)
  228. self.redis_com.zrem(self.m_tracker_key, task_id)
  229. # === 核心:成功次数判断 ===
  230. task.successful_bookings += 1
  231. max_b = self.m_cfg.booker.max_bookings_per_account
  232. if max_b > 0 and task.successful_bookings >= max_b:
  233. self._log(f"Account reached max bookings ({max_b}). Destroying instance.")
  234. self._remove_task(task, "max bookings reached")
  235. else:
  236. self._log(f"❌ BOOK FAILED for Order: {order_id}")
  237. except Exception as e:
  238. err_str = str(e)
  239. self._log(f"Exception during booking: {err_str}")
  240. rate_limited_indicators = [
  241. "42901" in err_str,
  242. "Rate limited" in err_str
  243. ]
  244. if any(rate_limited_indicators):
  245. is_rate_limited = True
  246. self._remove_task(task, "booking rate limited")
  247. if task_data and task_id is not None:
  248. task_meta = task_data.get('meta') or {}
  249. t_fails = task_meta.get('booking_failures', 0) + 1
  250. task_meta['booking_failures'] = t_fails
  251. try:
  252. VSCloudApi.Instance().update_vas_task(task_id, {"meta": task_meta})
  253. except Exception as cloud_err:
  254. self._log(f"Failed to update task meta: {cloud_err}")
  255. t_cd = self.task_backoff.calculate(t_fails)
  256. self._log(f"⏳ Task={task_id} (Booking Attempt {t_fails}) suspended for {t_cd:.1f}s.")
  257. self.redis_com.zadd(self.m_tracker_key, {str(task_id): time.time() + t_cd})
  258. finally:
  259. if not booking_success and task_id is not None and not is_rate_limited:
  260. self.redis_com.zadd(self.m_tracker_key, {str(task_id): 0})
  261. self._log(f"♻️ Task={task_id} normal failure. Instantly handed over to Sweeper.")
  262. def _creator_loop(self):
  263. self._log("Creator loop started.")
  264. spawn_interval = 10.0
  265. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  266. while not self.m_stop_event.is_set():
  267. time.sleep(2.0)
  268. if self.redis_com.exists(group_cd_key):
  269. continue
  270. with self.m_lock:
  271. current = len(self.m_tasks)
  272. pending = self.m_pending_builtin
  273. target = self.m_cfg.booker.target_instances
  274. if (current + pending) < target:
  275. now = time.time()
  276. if now - self.m_last_spawn_time >= spawn_interval:
  277. self.m_last_spawn_time = now
  278. self._spawn_worker()
  279. def _spawn_worker(self):
  280. with self.m_lock:
  281. self.m_pending_builtin += 1
  282. def _job():
  283. try:
  284. plg_cfg = VSPlgConfig()
  285. plg_cfg.debug = self.m_cfg.debug
  286. plg_cfg.free_config = self.m_cfg.free_config
  287. plg_cfg.session_max_life = self.m_cfg.session_max_life
  288. if self.m_cfg.need_account:
  289. acc = VSCloudApi.Instance().get_next_account(self.m_cfg.booker.account_pool_id, self.m_cfg.booker.account_cd)
  290. plg_cfg.account.id = acc['id']
  291. plg_cfg.account.username = acc['username']
  292. plg_cfg.account.password = acc['password']
  293. if self.m_cfg.need_proxy:
  294. proxy = VSCloudApi.Instance().get_next_proxy(self.m_cfg.proxy_pool, self.m_cfg.proxy_cd)
  295. plg_cfg.proxy.id = proxy['id']
  296. plg_cfg.proxy.ip = proxy['ip']
  297. plg_cfg.proxy.port = proxy['port']
  298. plg_cfg.proxy.proto = proxy['proto']
  299. plg_cfg.proxy.username = proxy['username']
  300. plg_cfg.proxy.password = proxy['password']
  301. instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
  302. instance.set_log(self.m_logger)
  303. instance.set_config(plg_cfg)
  304. instance.create_session()
  305. with self.m_lock:
  306. all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
  307. self.m_tasks.append(
  308. Task(
  309. instance=instance,
  310. qw_cfg=self.m_cfg.query_wait,
  311. next_run=time.time(),
  312. task_ref=None,
  313. acceptable_routing_keys=all_keys,
  314. source_queue="built-in",
  315. book_allowed=True,
  316. next_remote_ping = time.time() + random.randint(180, 300)
  317. )
  318. )
  319. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  320. self.redis_com.delete(group_fail_key)
  321. self._log(f"+++ Built-in Booker spawned: {plg_cfg.account.username}")
  322. except Exception as e:
  323. err_str = str(e)
  324. resource_not_found_indicators = [
  325. "40401" in err_str,
  326. "Account not found" in err_str,
  327. "Proxy not found" in err_str,
  328. ]
  329. if any(resource_not_found_indicators):
  330. return
  331. self._log(f"Spawn failed: {e}")
  332. rate_limited_indicators = [
  333. "42901" in err_str,
  334. "Rate limited" in err_str
  335. ]
  336. if any(rate_limited_indicators):
  337. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  338. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  339. # 更新全局(机器组)失败次数
  340. g_fails = self.redis_com.incr(group_fail_key)
  341. # 计算退避时间
  342. g_cd = self.group_backoff.calculate(g_fails)
  343. # 设置 Redis 全局冷却保护阀
  344. self.redis_com.set(group_cd_key, "1", ex=int(g_cd))
  345. self._log(f"📉 [Rate Limited] Group '{self.m_cfg.identifier}' failed {g_fails} times. Global Backoff: {g_cd:.1f}s.")
  346. finally:
  347. with self.m_lock:
  348. self.m_pending_builtin = max(0, self.m_pending_builtin - 1)
  349. ThreadPool.getInstance().enqueue(_job)