binding_manager.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # toolkit/binding_manager.py
  2. import threading
  3. from typing import List, Optional
  4. from vs_log_macros import VSC_DEBUG, VSC_INFO # type: ignore
  5. class BindingManager:
  6. """模拟账户-代理绑定管理器。"""
  7. _instance = None
  8. _lock = threading.Lock()
  9. def __new__(cls):
  10. with cls._lock:
  11. if cls._instance is None:
  12. cls._instance = super().__new__(cls)
  13. cls._instance._bindings = {} # { (account_pool, account_id): (proxy_pool, proxy_id, bind_type) }
  14. cls._instance._binding_lock = threading.Lock()
  15. return cls._instance
  16. @staticmethod
  17. def Instance():
  18. return BindingManager()
  19. def get_bounded_proxy_id(self, account_pool: str, account_id: int) -> Optional[int]:
  20. """获取给定账户绑定的代理ID。"""
  21. with self._binding_lock:
  22. key = (account_pool, account_id)
  23. binding = self._bindings.get(key)
  24. if binding:
  25. VSC_DEBUG("binding_manager", "Found binding for account %d: proxy %d", account_id, binding[1])
  26. return binding[1]
  27. VSC_DEBUG("binding_manager", "No binding found for account %d in pool %s", account_id, account_pool)
  28. return None
  29. def get_bounded_proxies_ids(self, account_pool: str, proxy_pool: str) -> List[int]:
  30. """获取所有在特定代理池中被账户绑定的代理ID列表。"""
  31. with self._binding_lock:
  32. bounded_ids = []
  33. for (acc_pool, _), (p_pool, p_id, _) in self._bindings.items():
  34. if acc_pool == account_pool and p_pool == proxy_pool:
  35. bounded_ids.append(p_id)
  36. VSC_DEBUG("binding_manager", "Bounded proxy IDs in pool %s for acc pool %s: %s", proxy_pool, account_pool, bounded_ids)
  37. return bounded_ids
  38. def create_binding(self, account_pool: str, account_id: int,
  39. proxy_pool: str, proxy_id: int, bind_type: str):
  40. """创建账户和代理的绑定。"""
  41. with self._binding_lock:
  42. key = (account_pool, account_id)
  43. self._bindings[key] = (proxy_pool, proxy_id, bind_type)
  44. VSC_INFO("binding_manager", "Created binding: account %d (pool %s) -> proxy %d (pool %s) type %s",
  45. account_id, account_pool, proxy_id, proxy_pool, bind_type)
  46. def remove_binding(self, account_pool: str, account_id: int):
  47. """移除账户和代理的绑定。"""
  48. with self._binding_lock:
  49. key = (account_pool, account_id)
  50. if key in self._bindings:
  51. del self._bindings[key]
  52. VSC_INFO("binding_manager", "Removed binding for account %d in pool %s", account_id, account_pool)