|
@@ -3,14 +3,15 @@ import time
|
|
|
import json
|
|
import json
|
|
|
import threading
|
|
import threading
|
|
|
import random
|
|
import random
|
|
|
-from datetime import datetime
|
|
|
|
|
|
|
+from datetime import datetime, timedelta, timezone
|
|
|
from typing import List, Dict, Callable, Optional
|
|
from typing import List, Dict, Callable, Optional
|
|
|
|
|
|
|
|
from core_types import (
|
|
from core_types import (
|
|
|
GroupConfig, PluginConfig, Account, Task, BookResult, QueryResult,
|
|
GroupConfig, PluginConfig, Account, Task, BookResult, QueryResult,
|
|
|
AppointmentType, QueryWaitMode, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str,
|
|
AppointmentType, QueryWaitMode, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str,
|
|
|
BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
|
|
BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
|
|
|
- NetworkTimeoutError
|
|
|
|
|
|
|
+ NetworkTimeoutError, BizLogicError, AccountStateError, AccountAuthError,
|
|
|
|
|
+ AccountBannedError, AccountIncompleteError, AccountNotFoundError, normalize_error
|
|
|
)
|
|
)
|
|
|
from plugin_factory import PluginFactory
|
|
from plugin_factory import PluginFactory
|
|
|
from toolkit.cloud_api import CloudApi
|
|
from toolkit.cloud_api import CloudApi
|
|
@@ -22,7 +23,7 @@ from utils.safe_redis_cli import SafeRedisClient
|
|
|
|
|
|
|
|
class BaseBookerGCO:
|
|
class BaseBookerGCO:
|
|
|
"""
|
|
"""
|
|
|
- Booker 基类,封装公共的基础设施与通用的生命周期管理、逻辑循环等。
|
|
|
|
|
|
|
+ Base Booker class encapsulating shared infrastructure, lifecycle management, and logic loops.
|
|
|
"""
|
|
"""
|
|
|
TAG = "BOOKER"
|
|
TAG = "BOOKER"
|
|
|
|
|
|
|
@@ -86,7 +87,7 @@ class BaseBookerGCO:
|
|
|
self._start_additional_threads()
|
|
self._start_additional_threads()
|
|
|
|
|
|
|
|
def _start_additional_threads(self):
|
|
def _start_additional_threads(self):
|
|
|
- """子类扩展线程的 Hook"""
|
|
|
|
|
|
|
+ """Hook for subclasses to start additional background threads."""
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
def stop(self):
|
|
def stop(self):
|
|
@@ -95,7 +96,7 @@ class BaseBookerGCO:
|
|
|
self._cleanup_all_tasks("booker stop")
|
|
self._cleanup_all_tasks("booker stop")
|
|
|
|
|
|
|
|
def update_config(self, new_cfg: GroupConfig):
|
|
def update_config(self, new_cfg: GroupConfig):
|
|
|
- """动态更新配置"""
|
|
|
|
|
|
|
+ """Dynamically updates the configuration."""
|
|
|
with self.m_lock:
|
|
with self.m_lock:
|
|
|
if self.m_cfg.enable and not new_cfg.enable:
|
|
if self.m_cfg.enable and not new_cfg.enable:
|
|
|
self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
|
|
self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
|
|
@@ -132,7 +133,7 @@ class BaseBookerGCO:
|
|
|
return removed
|
|
return removed
|
|
|
|
|
|
|
|
def _on_task_removed(self, task: Task):
|
|
def _on_task_removed(self, task: Task):
|
|
|
- """子类在 task 被移除时的自定义 Hook(如清理缓存)"""
|
|
|
|
|
|
|
+ """Hook for subclasses when a task is removed (e.g. cleaning up caches)."""
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
def _cleanup_all_tasks(self, reason: str = ""):
|
|
def _cleanup_all_tasks(self, reason: str = ""):
|
|
@@ -144,33 +145,14 @@ class BaseBookerGCO:
|
|
|
self._cleanup_task(task, reason)
|
|
self._cleanup_task(task, reason)
|
|
|
|
|
|
|
|
def _on_all_tasks_cleaned(self):
|
|
def _on_all_tasks_cleaned(self):
|
|
|
- """子类在所有 task 被清空时的自定义 Hook"""
|
|
|
|
|
|
|
+ """Hook for subclasses when all tasks are cleared."""
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
def _get_redis_key(self, routing_key: str) -> str:
|
|
def _get_redis_key(self, routing_key: str) -> str:
|
|
|
return f"vs:signal:{routing_key}"
|
|
return f"vs:signal:{routing_key}"
|
|
|
|
|
|
|
|
- def _normalize_error(self, err: Exception) -> BizException:
|
|
|
|
|
- """规整化异常为领域异常 BizException,保留对历史特征字符串的兜底兼容"""
|
|
|
|
|
- err_str = str(err)
|
|
|
|
|
- # 如果是底层网络/CORS预检被拒导致的 Fetch 失败或 WAF 阻断,精准提升为 PermissionDeniedError
|
|
|
|
|
- if "Failed to fetch" in err_str or "Status: 0" in err_str or "WAF Blocked" in err_str or "cf-mitigated" in err_str:
|
|
|
|
|
- return PermissionDeniedError(message=err_str)
|
|
|
|
|
- if isinstance(err, BizException):
|
|
|
|
|
- return 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 _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
|
|
def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
|
|
|
- """安全归还账号:将云端冷却时间重置为 0,避免非账号问题导致账号被误锁 3 小时"""
|
|
|
|
|
|
|
+ """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"):
|
|
if acc and acc.id > 0 and acc.username not in ("", "Guest"):
|
|
|
try:
|
|
try:
|
|
|
CloudApi.Instance().lock_account(acc.id, 0)
|
|
CloudApi.Instance().lock_account(acc.id, 0)
|
|
@@ -178,6 +160,35 @@ class BaseBookerGCO:
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
self._log(f"Failed to release account [{acc.username}]: {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(
|
|
def _dispatch_error_policy(
|
|
|
self,
|
|
self,
|
|
|
action: str,
|
|
action: str,
|
|
@@ -187,20 +198,53 @@ class BaseBookerGCO:
|
|
|
task_id: Optional[int] = None
|
|
task_id: Optional[int] = None
|
|
|
) -> None:
|
|
) -> None:
|
|
|
"""
|
|
"""
|
|
|
- Booker 错误调度与自愈策略引擎 (Policy Engine):
|
|
|
|
|
- 基于 (Action, 异常事实类型) 矩阵 + Booker 模式闭环执行自愈动作:
|
|
|
|
|
- - spawn/login 时 429:判定为账号级限流,锁定账号,更新 Redis 订单/任务追踪器与生成冷却;
|
|
|
|
|
- - book 时 429:档期提交频控或出口 IP 限制,不锁定账号,移除任务以轮换代理或重试;
|
|
|
|
|
- - session expired / 401:会话失效,移除任务;
|
|
|
|
|
- - 403 Forbidden / WAF:判定为 IP 受阻,移除任务以轮换代理;在 spawn 时立即安全释放账号;
|
|
|
|
|
- - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。
|
|
|
|
|
|
|
+ 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 = self._normalize_error(err)
|
|
|
|
|
|
|
+ biz_err = normalize_error(err)
|
|
|
active_plg_cfg = plg_cfg or (task.instance.config if task else None)
|
|
active_plg_cfg = plg_cfg or (task.instance.config if task else None)
|
|
|
acc = active_plg_cfg.account if active_plg_cfg else None
|
|
acc = active_plg_cfg.account if active_plg_cfg else None
|
|
|
|
|
|
|
|
- # 1. 目标站限流 / 429
|
|
|
|
|
- if isinstance(biz_err, RateLimiteddError):
|
|
|
|
|
|
|
+ # 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"):
|
|
if action in ("spawn", "login", "create_session"):
|
|
|
backoff = float(self.m_cfg.login_backoff)
|
|
backoff = float(self.m_cfg.login_backoff)
|
|
|
self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
|
|
self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
|
|
@@ -220,7 +264,7 @@ class BaseBookerGCO:
|
|
|
self._remove_task(task, "spawn account rate limited")
|
|
self._remove_task(task, "spawn account rate limited")
|
|
|
|
|
|
|
|
elif action == "book":
|
|
elif action == "book":
|
|
|
- # 预订提交时 429:接口频控或 IP 限制,绝不锁账号,移除实例以更换代理重试
|
|
|
|
|
|
|
+ # 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...")
|
|
self._log("🔄 [Booking Rate Limited] 429 during booking (Slot/IP throttled, Account preserved). Removing task to rotate proxy...")
|
|
|
if task:
|
|
if task:
|
|
|
self._remove_task(task, "booking rate limited")
|
|
self._remove_task(task, "booking rate limited")
|
|
@@ -229,7 +273,7 @@ class BaseBookerGCO:
|
|
|
if task:
|
|
if task:
|
|
|
self._remove_task(task, f"{action} rate limited")
|
|
self._remove_task(task, f"{action} rate limited")
|
|
|
|
|
|
|
|
- # 2. 会话过期 / 401
|
|
|
|
|
|
|
+ # 2. Session expired / 401
|
|
|
elif isinstance(biz_err, SessionExpiredOrInvalidError):
|
|
elif isinstance(biz_err, SessionExpiredOrInvalidError):
|
|
|
if action in ("spawn", "login", "create_session"):
|
|
if action in ("spawn", "login", "create_session"):
|
|
|
self._log(f"❌ [Auth Failed] Booker spawn failed (401). Cooling down spawn for 5s...")
|
|
self._log(f"❌ [Auth Failed] Booker spawn failed (401). Cooling down spawn for 5s...")
|
|
@@ -239,7 +283,7 @@ class BaseBookerGCO:
|
|
|
if task:
|
|
if task:
|
|
|
self._remove_task(task, f"{action} session expired")
|
|
self._remove_task(task, f"{action} session expired")
|
|
|
|
|
|
|
|
- # 3. 权限被拒 / WAF 拦截 / 403
|
|
|
|
|
|
|
+ # 3. Permission denied / WAF blocked / 403
|
|
|
elif isinstance(biz_err, PermissionDeniedError):
|
|
elif isinstance(biz_err, PermissionDeniedError):
|
|
|
proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
|
|
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...")
|
|
self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
|
|
@@ -249,7 +293,7 @@ class BaseBookerGCO:
|
|
|
self._release_account_safely(acc, reason="WAF Blocked")
|
|
self._release_account_safely(acc, reason="WAF Blocked")
|
|
|
self.m_spawn_cooldown_until = time.time() + proxy_cd
|
|
self.m_spawn_cooldown_until = time.time() + proxy_cd
|
|
|
|
|
|
|
|
- # 4. 网络或浏览器超时
|
|
|
|
|
|
|
+ # 4. Network or browser timeout
|
|
|
elif isinstance(biz_err, NetworkTimeoutError):
|
|
elif isinstance(biz_err, NetworkTimeoutError):
|
|
|
self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
|
|
self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
|
|
|
if task:
|
|
if task:
|
|
@@ -258,7 +302,7 @@ class BaseBookerGCO:
|
|
|
self._release_account_safely(acc, reason="Network Timeout")
|
|
self._release_account_safely(acc, reason="Network Timeout")
|
|
|
self.m_spawn_cooldown_until = time.time() + 10.0
|
|
self.m_spawn_cooldown_until = time.time() + 10.0
|
|
|
|
|
|
|
|
- # 5. 兜底策略
|
|
|
|
|
|
|
+ # 5. Fallback policy
|
|
|
else:
|
|
else:
|
|
|
self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
|
|
self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
|
|
|
if action in ("spawn", "login", "create_session"):
|
|
if action in ("spawn", "login", "create_session"):
|
|
@@ -267,24 +311,19 @@ class BaseBookerGCO:
|
|
|
elif task:
|
|
elif task:
|
|
|
task.next_run = time.time() + 10.0
|
|
task.next_run = time.time() + 10.0
|
|
|
|
|
|
|
|
- # 6. 统一代理健康指标埋点
|
|
|
|
|
|
|
+ # 6. Proxy health metrics recording
|
|
|
if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
|
|
if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
|
|
|
- err_type = biz_err.message
|
|
|
|
|
- if isinstance(biz_err, PermissionDeniedError):
|
|
|
|
|
- if "403202" in err_type or "cf-mitigated" in err_type.lower() or "waf blocked" in err_type.lower():
|
|
|
|
|
- err_type = "cf-mitigated (403202)"
|
|
|
|
|
-
|
|
|
|
|
ProxyManager.Instance().mark_proxy_result(
|
|
ProxyManager.Instance().mark_proxy_result(
|
|
|
proxy=active_plg_cfg.proxy.model_dump(),
|
|
proxy=active_plg_cfg.proxy.model_dump(),
|
|
|
plugin_name=self.m_cfg.plugin_config.plugin_name,
|
|
plugin_name=self.m_cfg.plugin_config.plugin_name,
|
|
|
action=action,
|
|
action=action,
|
|
|
success=False,
|
|
success=False,
|
|
|
http_code=biz_err.http_status,
|
|
http_code=biz_err.http_status,
|
|
|
- error_type=err_type
|
|
|
|
|
|
|
+ error_type=biz_err.message
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
def _is_within_active_hours(self) -> bool:
|
|
def _is_within_active_hours(self) -> bool:
|
|
|
- """判断当前是否在允许创建实例的时间段内"""
|
|
|
|
|
|
|
+ """Checks if current time is within allowed operating hours."""
|
|
|
start_str = self.m_cfg.active_time_start
|
|
start_str = self.m_cfg.active_time_start
|
|
|
end_str = self.m_cfg.active_time_end
|
|
end_str = self.m_cfg.active_time_end
|
|
|
current_bj_time = datetime.utcnow().time()
|
|
current_bj_time = datetime.utcnow().time()
|
|
@@ -333,11 +372,11 @@ class BaseBookerGCO:
|
|
|
self._log(f'Maintain loop exception: {e}')
|
|
self._log(f'Maintain loop exception: {e}')
|
|
|
|
|
|
|
|
def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
|
|
def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
|
|
|
- """子类维护循环中对于健康/异常 Task 的额外处理"""
|
|
|
|
|
|
|
+ """Subclass hook for additional handling of healthy/dead tasks during maintenance."""
|
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
|
|
def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
|
|
|
- """判断 query_result 中的可用日期是否在 task 意向范围内(默认 True,Order 模式重写)"""
|
|
|
|
|
|
|
+ """Checks if available dates in query_result match task preferences (defaults to True)."""
|
|
|
return True
|
|
return True
|
|
|
|
|
|
|
|
def _booking_trigger_loop(self):
|
|
def _booking_trigger_loop(self):
|
|
@@ -394,7 +433,7 @@ class BaseBookerGCO:
|
|
|
raise NotImplementedError
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def _push_success_notification(self, task_id, order_id, book_res):
|
|
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 = {
|
|
grab_info = {
|
|
|
"account": book_res.account,
|
|
"account": book_res.account,
|
|
|
"session_id": book_res.session_id,
|
|
"session_id": book_res.session_id,
|
|
@@ -418,9 +457,9 @@ class BaseBookerGCO:
|
|
|
|
|
|
|
|
class BuiltinBookerGCO(BaseBookerGCO):
|
|
class BuiltinBookerGCO(BaseBookerGCO):
|
|
|
"""
|
|
"""
|
|
|
- 非绑定模式 (公共内置账号池):
|
|
|
|
|
- - 只维护全局 target_instances 数量的实例。
|
|
|
|
|
- - 所有实例热机等待,发现信号后临时去云端 Pop 订单。
|
|
|
|
|
|
|
+ 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"
|
|
TAG = "BUILTIN-BOOKER"
|
|
|
|
|
|
|
@@ -500,17 +539,24 @@ class BuiltinBookerGCO(BaseBookerGCO):
|
|
|
def _execute_book_job(self, task: Task, query_result: QueryResult):
|
|
def _execute_book_job(self, task: Task, query_result: QueryResult):
|
|
|
queue_name = f"auto.{query_result.apt_type.routing_key}"
|
|
queue_name = f"auto.{query_result.apt_type.routing_key}"
|
|
|
|
|
|
|
|
- task_id = None
|
|
|
|
|
task_data = None
|
|
task_data = None
|
|
|
-
|
|
|
|
|
try:
|
|
try:
|
|
|
task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
|
|
task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
|
|
|
- if not task_data:
|
|
|
|
|
- return
|
|
|
|
|
- task_id = task_data['id']
|
|
|
|
|
- order_id = task_data.get('order_id')
|
|
|
|
|
- self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + 30.0})
|
|
|
|
|
-
|
|
|
|
|
|
|
+ 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', {})
|
|
user_input = task_data.get('user_inputs', {})
|
|
|
book_res = task.instance.book(query_result, user_input)
|
|
book_res = task.instance.book(query_result, user_input)
|
|
|
|
|
|
|
@@ -531,10 +577,10 @@ class BuiltinBookerGCO(BaseBookerGCO):
|
|
|
|
|
|
|
|
class OrderBookerGCO(BaseBookerGCO):
|
|
class OrderBookerGCO(BaseBookerGCO):
|
|
|
"""
|
|
"""
|
|
|
- 绑定模式 (订单自带账号):
|
|
|
|
|
- - 按城市队列维护热机配额。
|
|
|
|
|
- - 绝对的 1 对 1 关系:一个实例绑定一个云端订单。
|
|
|
|
|
- - 预订成功后,实例立即销毁。
|
|
|
|
|
|
|
+ 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"
|
|
TAG = "ORDER-BOOKER"
|
|
|
|
|
|
|
@@ -660,7 +706,12 @@ class OrderBookerGCO(BaseBookerGCO):
|
|
|
plg_cfg = None
|
|
plg_cfg = None
|
|
|
try:
|
|
try:
|
|
|
queue_name = f"auto.{target_routing_key}"
|
|
queue_name = f"auto.{target_routing_key}"
|
|
|
- task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
|
|
|
|
|
|
|
+ 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:
|
|
if not task_data:
|
|
|
return
|
|
return
|
|
|
|
|
|