| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778 |
- import os
- import time
- import json
- import threading
- import random
- from datetime import datetime, timedelta, timezone
- from typing import List, Dict, Callable, Optional
- from core_types import (
- GroupConfig, PluginConfig, Account, Task, BookResult, QueryResult,
- AppointmentType, QueryWaitMode, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str,
- BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
- NetworkTimeoutError, BizLogicError, AccountStateError, AccountAuthError,
- AccountBannedError, AccountIncompleteError, AccountNotFoundError, normalize_error
- )
- from plugin_factory import PluginFactory
- from toolkit.cloud_api import CloudApi
- from toolkit.proxy_manager import ProxyManager
- from toolkit.thread_pool import ThreadPool
- from toolkit.notifier import notify_book_result
- from utils.safe_redis_cli import SafeRedisClient
- class BaseBookerGCO:
- """
- Base Booker class encapsulating shared infrastructure, lifecycle management, and logic loops.
- """
- TAG = "BOOKER"
- def __init__(self, cfg: GroupConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
- self.m_cfg = cfg
- self.m_factory = PluginFactory()
- self.m_logger = logger
- self.m_tasks: List[Task] = []
- self.m_lock = threading.RLock()
- self.m_stop_event = threading.Event()
- self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
- self.m_tracker_key = f"vs:worker:tasks_tracker:{self.m_cfg.identifier}"
- self.m_last_group_query_time = 0.0
- self.m_spawn_cooldown_until = 0.0
- def _log(self, message):
- 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_status(self) -> GroupStatus:
- with self.m_lock:
- tasks = list(self.m_tasks)
- gid = self.m_cfg.identifier
- enable = self.m_cfg.enable
- plugin_name = self.m_cfg.plugin_config.plugin_name
- plugins_status = []
- healthy_count = 0
- for t in tasks:
- if t and t.instance:
- st = t.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=len(tasks),
- healthy_tasks=healthy_count,
- plugins=plugins_status,
- updated_at=utc_now_str(),
- )
- def start(self):
- if not self.m_cfg.enable:
- return
- self._log(f"Starting {self.TAG}...")
- 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)
- threading.Thread(target=self._booking_trigger_loop, daemon=True).start()
- threading.Thread(target=self._creator_loop, daemon=True).start()
- threading.Thread(target=self._maintain_loop, daemon=True).start()
- self._start_additional_threads()
- def _start_additional_threads(self):
- """Hook for subclasses to start additional background threads."""
- pass
- def stop(self):
- self._log("Stopping Booker...")
- self.m_stop_event.set()
- self._cleanup_all_tasks("booker stop")
- def update_config(self, new_cfg: GroupConfig):
- """Dynamically updates the configuration."""
- with self.m_lock:
- if self.m_cfg.enable and not new_cfg.enable:
- self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
- 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 _cleanup_instance(self, instance, reason: str = "", task_ref=None):
- try:
- if instance:
- ref_str = f" for task={task_ref}" if task_ref else ""
- self._log(f"🧹 Cleaned up instance{ref_str}. Reason: {reason}")
- instance.cleanup()
- except Exception as e:
- self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
- def _cleanup_task(self, task: Task, reason: str = ""):
- if task and task.instance:
- self._cleanup_instance(task.instance, reason, task.task_ref)
- def _remove_task(self, task: Task, reason: str = "", cleanup: bool = True):
- removed = False
- with self.m_lock:
- if task in self.m_tasks:
- self.m_tasks.remove(task)
- removed = True
- self._on_task_removed(task)
-
- if cleanup and removed:
- self._cleanup_task(task, reason)
- return removed
- def _on_task_removed(self, task: Task):
- """Hook for subclasses when a task is removed (e.g. cleaning up caches)."""
- pass
- def _cleanup_all_tasks(self, reason: str = ""):
- with self.m_lock:
- tasks = list(self.m_tasks)
- self.m_tasks.clear()
- self._on_all_tasks_cleaned()
- for task in tasks:
- self._cleanup_task(task, reason)
- def _on_all_tasks_cleaned(self):
- """Hook for subclasses when all tasks are cleared."""
- pass
- def _get_redis_key(self, routing_key: str) -> str:
- return f"vs:signal:{routing_key}"
- def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
- """Safely releases account: resets cloud cooldown to 0 to prevent 3-hour lockouts caused by non-account issues."""
- if acc and acc.id > 0 and acc.username not in ("", "Guest"):
- try:
- CloudApi.Instance().lock_account(acc.id, 0)
- self._log(f"🔓 [Account Released] Account [{acc.username}] immediately released back to pool (Reason: {reason}).")
- except Exception as e:
- self._log(f"Failed to release account [{acc.username}]: {e}")
- def _disable_account_safely(self, acc: Optional[Account], reason: str = "") -> None:
- """Safely disables account in cloud: sets status='disable', locks for 10 years, and records extra_data."""
- if not acc or acc.id <= 0 or acc.username in ("", "Guest"):
- return
- try:
- cloud = CloudApi.Instance()
- url = f"{cloud.base_url}/api/account/update"
- params = {"account_id": acc.id}
- far_future = (datetime.now(timezone.utc) + timedelta(days=3650)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
- payload = {
- "status": "disable",
- "next_use_time": far_future,
- "extra_data": {
- "disable_reason": reason,
- "disabled_at": int(time.time()),
- "module": self.TAG,
- "group": getattr(self.m_cfg, "identifier", "")
- }
- }
- cloud._perform_request('PUT', url, params=params, json_data=payload, headers=cloud._get_headers(), timeout=10)
- self._log(f"🚫 [Account Disabled] Account [{acc.username}] (ID={acc.id}) permanently marked as 'disable' in Cloud API. Reason: {reason}")
- except Exception as e:
- self._log(f"Failed to set account status to disable via cloud API: {e}. Falling back to 10-year lock...")
- try:
- CloudApi.Instance().lock_account(acc.id, 86400 * 3650)
- except Exception as lock_err:
- self._log(f"Fallback 10-year lock also failed: {lock_err}")
- def _dispatch_error_policy(
- self,
- action: str,
- err: Exception,
- task: Optional[Task] = None,
- plg_cfg: Optional[PluginConfig] = None,
- task_id: Optional[int] = None
- ) -> None:
- """
- Booker error dispatch and self-healing policy engine:
- Executes self-healing actions based on the (action, error type) matrix:
- - AccountStateError (invalid credentials, banned, incomplete): Permanently disables pool account or fails order task, never releases back to pool.
- - 429 during spawn/login: Account-level rate limit. Locks account, updates tracker & cooldown.
- - 429 during book: Booking slot rate limit or egress IP throttle. Preserves account, removes task to rotate proxy.
- - 401 / session expired: Session invalidated. Removes task.
- - 403 Forbidden / WAF: IP blocked. Removes task to rotate proxy; safely releases account during spawn.
- - Handles logging and timer backoffs internally.
- """
- biz_err = normalize_error(err)
- active_plg_cfg = plg_cfg or (task.instance.config if task else None)
- acc = active_plg_cfg.account if active_plg_cfg else None
- # 0. Fatal Account State Error (credentials invalid, banned, incomplete, not found)
- if isinstance(biz_err, AccountStateError):
- self._log(f"🚨 [Account Fatal Error] {biz_err.__class__.__name__} during {action}: {biz_err.message} (code={biz_err.code})")
- effective_task_id = task_id if task_id is not None else (task.task_ref if task else None)
- # If bound order task, update VAS task status to failed
- if effective_task_id is not None:
- try:
- CloudApi.Instance().update_vas_task(str(effective_task_id), {
- "status": "failed",
- "fail_reason": f"Account fatal error: {biz_err.message} (code={biz_err.code})"
- })
- self._log(f"📋 VAS task [{effective_task_id}] marked as 'failed' due to account error: {biz_err.message}")
- except Exception as update_err:
- self._log(f"Failed to update VAS task status: {update_err}")
- try:
- self.redis_client.zrem(self.m_tracker_key, effective_task_id)
- except Exception as zrem_err:
- self._log(f"Failed to remove task from tracker: {zrem_err}")
- # If pool account, permanently disable it in cloud
- if acc and acc.id > 0 and acc.username not in ("", "Guest"):
- self._disable_account_safely(acc, reason=f"{biz_err.__class__.__name__}: {biz_err.message}")
- # Never release account back to pool
- if task:
- self._remove_task(task, f"account fatal error: {biz_err.message}")
- if action in ("spawn", "login", "create_session"):
- self.m_spawn_cooldown_until = time.time() + 5.0
- # 1. Target site rate limit / 429
- elif isinstance(biz_err, RateLimiteddError):
- if action in ("spawn", "login", "create_session"):
- backoff = float(self.m_cfg.login_backoff)
- self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
- if acc and acc.username not in ("", "Guest") and 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}")
- effective_task_id = task_id if task_id is not None else (task.task_ref if task else None)
- if effective_task_id is not None:
- self.redis_client.zadd(self.m_tracker_key, {str(effective_task_id): time.time() + self.m_cfg.login_backoff})
- self.m_spawn_cooldown_until = time.time() + backoff
- if task:
- self._remove_task(task, "spawn account rate limited")
- elif action == "book":
- # 429 during booking: slot rate limit or IP restriction, preserve account and remove task to rotate proxy
- self._log("🔄 [Booking Rate Limited] 429 during booking (Slot/IP throttled, Account preserved). Removing task to rotate proxy...")
- if task:
- self._remove_task(task, "booking rate limited")
- else:
- self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.")
- if task:
- self._remove_task(task, f"{action} rate limited")
- # 2. Session expired / 401
- elif isinstance(biz_err, SessionExpiredOrInvalidError):
- if action in ("spawn", "login", "create_session"):
- self._log(f"❌ [Auth Failed] Booker spawn failed (401). Cooling down spawn for 5s...")
- self.m_spawn_cooldown_until = time.time() + 5.0
- else:
- self._log(f"🔄 [Session Expired] Booker session died during {action}. Removing task...")
- if task:
- self._remove_task(task, f"{action} session expired")
- # 3. Permission denied / WAF blocked / 403
- elif isinstance(biz_err, PermissionDeniedError):
- proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
- self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
- if task:
- self._remove_task(task, f"{action} waf blocked")
- if action in ("spawn", "login", "create_session"):
- self._release_account_safely(acc, reason="WAF Blocked")
- self.m_spawn_cooldown_until = time.time() + proxy_cd
- # 4. Network or browser timeout
- elif isinstance(biz_err, NetworkTimeoutError):
- self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
- if task:
- task.next_run = time.time() + 5.0
- if action in ("spawn", "login", "create_session"):
- self._release_account_safely(acc, reason="Network Timeout")
- self.m_spawn_cooldown_until = time.time() + 10.0
- # 5. Fallback policy
- else:
- self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
- if action in ("spawn", "login", "create_session"):
- self._release_account_safely(acc, reason=f"Unexpected error: {biz_err.message}")
- self.m_spawn_cooldown_until = time.time() + 10.0
- elif task:
- task.next_run = time.time() + 10.0
- # 6. Proxy health metrics recording
- if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
- ProxyManager.Instance().mark_proxy_result(
- proxy=active_plg_cfg.proxy.model_dump(),
- plugin_name=self.m_cfg.plugin_config.plugin_name,
- action=action,
- success=False,
- http_code=biz_err.http_status,
- error_type=biz_err.message
- )
- def _is_within_active_hours(self) -> bool:
- """Checks if current time is within allowed operating hours."""
- 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 _maintain_loop(self):
- self._log("Maintain loop started.")
- while not self.m_stop_event.is_set():
- try:
- time.sleep(1.0)
- with self.m_lock:
- tasks_to_check = list(self.m_tasks)
-
- if not tasks_to_check:
- continue
-
- dead_tasks = []
- healthy_tasks = []
- now = time.time()
- for t in tasks_to_check:
- if now >= t.next_remote_ping:
- t.instance.keep_alive()
- if t.instance.health_check():
- healthy_tasks.append(t)
- t.next_remote_ping = now + random.gauss(self.m_cfg.booker.keep_alive, 5)
- else:
- dead_tasks.append(t)
- else:
- healthy_tasks.append(t)
-
- self._on_maintain_ping(healthy_tasks, dead_tasks)
- if dead_tasks:
- with self.m_lock:
- current_tasks = list(self.m_tasks)
- self.m_tasks = [t for t in self.m_tasks if t in healthy_tasks]
- for t in dead_tasks:
- if t in current_tasks:
- self._cleanup_task(t, "unhealthy or keep-alive failed")
- else:
- with self.m_lock:
- self.m_tasks = [t for t in self.m_tasks if t in healthy_tasks]
- except Exception as e:
- self._log(f'Maintain loop exception: {e}')
- def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
- """Subclass hook for additional handling of healthy/dead tasks during maintenance."""
- pass
- def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
- """Checks if available dates in query_result match task preferences (defaults to True)."""
- return True
- def _booking_trigger_loop(self):
- self._log("Trigger loop started.")
- while not self.m_stop_event.is_set():
- try:
- time.sleep(0.1)
- now = time.time()
- for apt_type in self.m_cfg.appointment_types:
- redis_key = self._get_redis_key(apt_type.routing_key)
- raw_data = self.redis_client.get(redis_key)
- if not raw_data:
- continue
- try:
- data = json.loads(raw_data)
- query_result = QueryResult.model_validate(data['query_result'])
- query_result.apt_type = AppointmentType.model_validate(data['apt_type'])
- except Exception as parse_err:
- self._log(f"Data parsing error for {redis_key}: {parse_err}. Deleting corrupted signal.")
- self.redis_client.delete(redis_key)
- continue
-
- matching_tasks = []
- with self.m_lock:
- for task in self.m_tasks:
- if now < task.next_run or not task.book_allowed:
- continue
- if apt_type.routing_key not in task.acceptable_routing_keys:
- continue
- if not self._is_date_of_interest(task, query_result):
- continue
-
- task.next_run = now + self.m_cfg.booker.booking_cooldown
- matching_tasks.append(task)
-
- if matching_tasks:
- threads = []
- for task in matching_tasks:
- self._log(f"🚀 Triggering BOOK for {apt_type.routing_key} | Order Ref: {task.task_ref}")
- t = threading.Thread(target=self._execute_book_job, args=(task, query_result))
- threads.append(t)
- t.start()
-
- for t in threads:
- t.join()
-
- except Exception as e:
- self._log(f"Booking trigger loop exception: {e}")
- def _execute_book_job(self, task: Task, query_result: QueryResult):
- raise NotImplementedError
- def _creator_loop(self):
- raise NotImplementedError
- def _push_success_notification(self, task_id, order_id, book_res):
- """Shared helper to sync booking success state to cloud and dispatch notifications."""
- grab_info = {
- "account": book_res.account,
- "session_id": book_res.session_id,
- "urn": book_res.urn,
- "slot_date": book_res.book_date,
- "slot_time": book_res.book_time,
- "timestamp": int(time.time()),
- "payment_link": book_res.payment_link
- }
-
- def _update_cloud_success():
- try:
- CloudApi.Instance().update_vas_task(str(task_id), {"status": "grabbed", "grabbed_history": grab_info})
- except Exception as e:
- self._log(f"Failed to update success state to cloud: {e}")
- ThreadPool.getInstance().enqueue(_update_cloud_success)
- notify_book_result(book_res, order_id=str(order_id) if order_id else None, logger=self._log)
- self.redis_client.zrem(self.m_tracker_key, task_id)
- class BuiltinBookerGCO(BaseBookerGCO):
- """
- Unbound mode (shared built-in account pool):
- - Maintains target_instances count of instances globally.
- - Instances stay warm; when a slot signal is detected, orders are popped on-demand from the cloud queue.
- """
- TAG = "BUILTIN-BOOKER"
- def _creator_loop(self):
- self._log("Creator loop started.")
- while not self.m_stop_event.wait(1.0):
- if not self._is_within_active_hours():
- continue
- if time.time() < self.m_spawn_cooldown_until:
- continue
-
- with self.m_lock:
- current = len(self.m_tasks)
- target = self.m_cfg.booker.target_instances
- if current < target:
- self._spawn_worker()
- def _spawn_worker(self):
- instance = None
- task = None
- success = False
- plg_cfg = None
-
- try:
- plg_cfg = PluginConfig()
- plg_cfg.debug = self.m_cfg.debug
- plg_cfg.free_config = self.m_cfg.free_config
- plg_cfg.session_max_life = self.m_cfg.session_max_life
- if self.m_cfg.need_account:
- acc = CloudApi.Instance().get_next_account(self.m_cfg.booker.account_pool_id, self.m_cfg.booker.account_cd)
- plg_cfg.account = type(plg_cfg.account)(**acc)
- if self.m_cfg.need_proxy:
- proxy = ProxyManager.Instance().get_next_proxy(
- self.m_cfg.proxy_pool,
- self.m_cfg.proxy_cd,
- plugin_name=self.m_cfg.plugin_config.plugin_name
- )
- plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
- instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
- instance.set_log(self.m_logger)
- instance.set_config(plg_cfg)
- instance.create_session()
- all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
- task = Task(
- instance=instance,
- next_run=time.time(),
- task_ref=None,
- acceptable_routing_keys=all_keys,
- source_queue="built-in",
- book_allowed=True,
- next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5)
- )
- with self.m_lock:
- self.m_tasks.append(task)
- success = True
- if plg_cfg.proxy.port > 0:
- ProxyManager.Instance().mark_proxy_result(
- proxy=plg_cfg.proxy.model_dump(),
- plugin_name=self.m_cfg.plugin_config.plugin_name,
- action="spawn",
- success=True,
- http_code=200
- )
- self._log(f"+++ Built-in Booker spawned: {plg_cfg.account.username}")
- except Exception as e:
- self._dispatch_error_policy("spawn", e, plg_cfg=plg_cfg)
- finally:
- if not success and instance:
- self._cleanup_instance(instance, "spawn failed")
- def _execute_book_job(self, task: Task, query_result: QueryResult):
- queue_name = f"auto.{query_result.apt_type.routing_key}"
- task_data = None
- try:
- task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
- except BizLogicError:
- # Queue has no pending tasks, return normally
- return
- except Exception as e:
- self._log(f"⚠️ [CloudApi] Failed to pop task from {queue_name}: {e}")
- return
- if not task_data:
- return
- task_id = task_data.get('id')
- order_id = task_data.get('order_id')
- self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + 30.0})
-
- try:
- user_input = task_data.get('user_inputs', {})
- book_res = task.instance.book(query_result, user_input)
-
- if book_res.success:
- self._log(f"✅ BOOK SUCCESS! Order: {order_id}")
- self._push_success_notification(task_id, order_id, book_res)
-
- task.successful_bookings += 1
- max_b = self.m_cfg.booker.max_bookings_per_account
- if max_b > 0 and task.successful_bookings >= max_b:
- self._log(f"Account reached max bookings ({max_b}). Destroying instance.")
- self._remove_task(task, "max bookings reached")
- else:
- self._log(f"❌ BOOK FAILED for Order: {order_id}")
- except Exception as e:
- self._dispatch_error_policy("book", e, task=task)
- class OrderBookerGCO(BaseBookerGCO):
- """
- Bound mode (order provides its own account credentials):
- - Maintains warm-up quotas per routing queue.
- - Strict 1:1 binding: one instance per cloud order.
- - Instance is destroyed immediately after booking completes.
- """
- TAG = "ORDER-BOOKER"
- def __init__(self, cfg: GroupConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
- super().__init__(cfg, redis_conf, logger)
- self.m_task_data_cache: Dict[str, dict] = {}
- self.heartbeat_ttl = 2 * 60.0
- def _start_additional_threads(self):
- threading.Thread(target=self._cache_refresh_loop, daemon=True).start()
- def _on_task_removed(self, task: Task):
- task_id = task.task_ref
- if task_id:
- self.m_task_data_cache.pop(str(task_id), None)
- def _on_all_tasks_cleaned(self):
- self.m_task_data_cache.clear()
- def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
- if healthy_tasks:
- new_deadline = time.time() + self.heartbeat_ttl
- mapping = {str(t.task_ref): new_deadline for t in healthy_tasks}
- self.redis_client.bulk_zadd(self.m_tracker_key, mapping)
- if dead_tasks:
- mapping = {str(t.task_ref): 0 for t in dead_tasks}
- self.redis_client.bulk_zadd(self.m_tracker_key, mapping)
- def _cache_refresh_loop(self):
- self._log("Cache refresh loop started.")
- refresh_interval = 15 * 60
-
- while not self.m_stop_event.is_set():
- try:
- time.sleep(1)
- with self.m_lock:
- tasks_to_check = {
- tid: data.get('_last_refresh', 0)
- for tid, data in self.m_task_data_cache.items()
- }
-
- if not tasks_to_check:
- continue
-
- now = time.time()
- for tid, last_refresh in tasks_to_check.items():
- if now - last_refresh >= refresh_interval:
- fresh_data = CloudApi.Instance().get_vas_task(tid)
- if fresh_data:
- fresh_data['_last_refresh'] = time.time()
-
- with self.m_lock:
- if tid in self.m_task_data_cache:
- self.m_task_data_cache[tid] = fresh_data
- time.sleep(0.5)
- except Exception as e:
- self._log(f'Cache refresh loop exception: {e}')
- def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
- if query_result.availability_status != AvailabilityStatus.Available:
- return True
- task_id = task.task_ref
- task_data = self.m_task_data_cache.get(str(task_id), {})
- user_input = task_data.get('user_inputs', {})
- expected_end_date = (
- user_input.get('expected_end_date')
- or '2100-01-01'
- )
- available_date = query_result.earliest_date
- dt = available_date.strftime("%Y-%m-%d")
- return dt <= expected_end_date
- def _execute_book_job(self, task: Task, query_result: QueryResult):
- task_id = task.task_ref
- task_data = None
- try:
- with self.m_lock:
- task_data = self.m_task_data_cache.get(str(task_id))
- if not task_data or task_data.get('status') in ['grabbed', 'pause', 'completed', 'cancelled']:
- self._log(f"Bound Task={task_id} is no longer valid or already processed. Removing instance.")
- self._remove_task(task, "bound task no longer valid")
- self.redis_client.zrem(self.m_tracker_key, task_id)
- return
-
- order_id = task_data.get('order_id')
- user_input = task_data.get('user_inputs', {})
- book_res = task.instance.book(query_result, user_input)
- if book_res.success:
- self._log(f"✅ BOOK SUCCESS! Order: {order_id}. Destroying instance.")
- self._push_success_notification(task_id, order_id, book_res)
- self._remove_task(task, "booking success")
- else:
- self._log(f"❌ BOOK FAILED for Order: {order_id}. Will retry on next signal.")
- except Exception as e:
- self._dispatch_error_policy("book", e, task=task)
- def _creator_loop(self):
- self._log("Creator loop started.")
- while not self.m_stop_event.wait(1.0):
- if not self._is_within_active_hours():
- continue
- if time.time() < self.m_spawn_cooldown_until:
- continue
- for apt in self.m_cfg.appointment_types:
- r_key = apt.routing_key
- with self.m_lock:
- active = sum(1 for t in self.m_tasks if t.source_queue == r_key)
- target = self.m_cfg.booker.target_instances
- if active < target:
- self._spawn_worker(r_key)
- def _spawn_worker(self, target_routing_key: str):
- instance = None
- task = None
- success = False
- task_id = None
- plg_cfg = None
- try:
- queue_name = f"auto.{target_routing_key}"
- try:
- task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
- except BizLogicError:
- # Queue has no pending tasks, return directly
- return
- if not task_data:
- return
-
- task_id = task_data['id']
-
- with self.m_lock:
- self.m_task_data_cache[str(task_id)] = task_data
-
- self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + 8*60.0})
- user_inputs = task_data.get('user_inputs', {})
-
- plg_cfg = PluginConfig()
- plg_cfg.debug = self.m_cfg.debug
- plg_cfg.free_config = self.m_cfg.free_config
- plg_cfg.session_max_life = self.m_cfg.session_max_life
- plg_cfg.account.username = user_inputs.get("username", "")
- plg_cfg.account.password = user_inputs.get("password", "")
- if not plg_cfg.account.username:
- return
-
- acceptable_keys = [target_routing_key]
- if self.m_cfg.need_proxy:
- proxy = ProxyManager.Instance().get_next_proxy(
- self.m_cfg.proxy_pool,
- self.m_cfg.proxy_cd,
- plugin_name=self.m_cfg.plugin_config.plugin_name
- )
- plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
- instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
- instance.set_log(self.m_logger)
- instance.set_config(plg_cfg)
- instance.create_session()
- task = Task(
- instance=instance,
- next_run=time.time(),
- task_ref=task_id,
- acceptable_routing_keys=acceptable_keys,
- source_queue=target_routing_key,
- book_allowed=True,
- next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5)
- )
- with self.m_lock:
- self.m_tasks.append(task)
- success = True
- if plg_cfg.proxy.port > 0:
- ProxyManager.Instance().mark_proxy_result(
- proxy=plg_cfg.proxy.model_dump(),
- plugin_name=self.m_cfg.plugin_config.plugin_name,
- action="spawn",
- success=True,
- http_code=200
- )
- self._log(f"+++ Order Booker spawned: {plg_cfg.account.username} (Target: {acceptable_keys})")
- except Exception as e:
- self._dispatch_error_policy("spawn", e, plg_cfg=plg_cfg, task_id=task_id)
- finally:
- if not success and instance:
- self._cleanup_instance(instance, "spawn failed")
- if not success and task_id:
- with self.m_lock:
- self.m_task_data_cache.pop(str(task_id), None)
|