Riy777 commited on
Commit
9d16b57
·
1 Parent(s): a519b54

Create rpc_manager.py

Browse files
Files changed (1) hide show
  1. whale_monitor/rpc_manager.py +229 -0
whale_monitor/rpc_manager.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # whale_monitor/rpc_manager.py
2
+ # هذا هو "الوكيل الذكي" لإدارة اتصالات RPC والمستكشفات
3
+
4
+ import asyncio
5
+ import httpx
6
+ import time
7
+ import ssl
8
+ import json
9
+ import os
10
+ from collections import deque, defaultdict
11
+ import random
12
+
13
+ # استيراد الإعدادات الثابتة
14
+ from .config import DEFAULT_NETWORK_CONFIGS, COINGECKO_BASE_URL
15
+
16
+ # إعدادات الوكيل الذكي
17
+ RPC_HEALTH_CHECK_WINDOW = 10 # تتبع آخر 10 طلبات
18
+ RPC_ERROR_THRESHOLD = 3 # عدد الأخطاء المتتالية لإيقاف مؤقت
19
+ RPC_CIRCUIT_BREAKER_DURATION = 300 # 5 دقائق إيقاف مؤقت
20
+
21
+ class AdaptiveRpcManager:
22
+ """
23
+ مدير RPC ذكي يتتبع صحة النقاط، ويدير حدود الطلبات،
24
+ ويختار أفضل نقطة متاحة تلقائياً.
25
+ """
26
+ def __init__(self, http_client: httpx.AsyncClient, api_keys: dict):
27
+ self.http_client = http_client
28
+ self.api_keys = api_keys
29
+
30
+ # منظمات الطلبات (Semaphores)
31
+ self.rpc_semaphore = asyncio.Semaphore(5) # حد عام لـ RPC
32
+ self.coingecko_semaphore = asyncio.Semaphore(1) # حد خاص لـ CoinGecko
33
+
34
+ # تهيئة إعدادات الشبكة ونقاط RPC
35
+ self.network_configs = self._initialize_network_configs(DEFAULT_NETWORK_CONFIGS)
36
+
37
+ # نظام تتبع الصحة (التعلم)
38
+ self.endpoint_health = defaultdict(lambda: defaultdict(lambda: {
39
+ "latency": deque(maxlen=RPC_HEALTH_CHECK_WINDOW),
40
+ "consecutive_errors": 0,
41
+ "total_errors": 0,
42
+ "last_error_time": None,
43
+ "circuit_open": False,
44
+ }))
45
+
46
+ print("✅ مدير RPC الذكي (الوكيل) مهيأ.")
47
+
48
+ def _initialize_network_configs(self, configs):
49
+ """
50
+ يقوم بحقن مفاتيح API في إعدادات الشبكة عند بدء التشغيل.
51
+ """
52
+ initialized_configs = {}
53
+ for network, config in configs.items():
54
+ new_config = config.copy()
55
+
56
+ # حقن مفاتيح RPC
57
+ new_config['rpc_endpoints'] = self._inject_api_keys(
58
+ config['rpc_endpoints'],
59
+ self.api_keys.get('infura')
60
+ )
61
+
62
+ # حقن مفاتيح المستكشف (Explorer)
63
+ if config.get('explorer'):
64
+ explorer_key_name = config['explorer'].get('api_key_name')
65
+ if explorer_key_name and explorer_key_name in self.api_keys:
66
+ new_config['explorer']['api_key'] = self.api_keys[explorer_key_name]
67
+ else:
68
+ new_config['explorer']['api_key'] = None # مفتاح غير متوفر
69
+
70
+ initialized_configs[network] = new_config
71
+ return initialized_configs
72
+
73
+ def _inject_api_keys(self, endpoints: list, infura_key: str):
74
+ """
75
+ يستبدل <INFURA_KEY> بالمفتاح الفعلي.
76
+ """
77
+ if not infura_key:
78
+ # إزالة النقاط التي تعتمد على مفتاح غير متوفر
79
+ return [ep for ep in endpoints if "<INFURA_KEY>" not in ep]
80
+
81
+ return [ep.replace("<INFURA_KEY>", infura_key) for ep in endpoints]
82
+
83
+ def get_network_configs(self):
84
+ """
85
+ إرجاع إعدادات الشبكة المهيأة (للاستخدام في core.py)
86
+ """
87
+ return self.network_configs
88
+
89
+ def get_explorer_config(self, network: str):
90
+ """
91
+ إرجاع إعدادات المستكشف (URL والمفتاح) لشبكة معينة.
92
+ """
93
+ config = self.network_configs.get(network, {})
94
+ return config.get('explorer')
95
+
96
+ def _get_healthy_endpoints(self, network: str):
97
+ """
98
+ "الذكاء" - يرتب نقاط RPC بناءً على الصحة.
99
+ يستبعد النقاط التي في وضع "قاطع الدائرة" (Circuit Breaker).
100
+ """
101
+ if network not in self.network_configs:
102
+ return []
103
+
104
+ endpoints = self.network_configs[network]['rpc_endpoints']
105
+ healthy_endpoints = []
106
+
107
+ current_time = time.time()
108
+
109
+ for ep in endpoints:
110
+ health = self.endpoint_health[network][ep]
111
+
112
+ # التحقق من قاطع الدائرة
113
+ if health['circuit_open']:
114
+ if current_time - health['last_error_time'] > RPC_CIRCUIT_BREAKER_DURATION:
115
+ # إعادة فتح الدائرة للمحاولة
116
+ health['circuit_open'] = False
117
+ health['consecutive_errors'] = 0
118
+ print(f"ℹ️ [RPC Manager] إعادة تفعيل نقطة RPC: {ep.split('//')[-1]}")
119
+ else:
120
+ continue # النقطة لا تزال معطلة مؤقتاً
121
+
122
+ # حساب متو��ط زمن الاستجابة
123
+ avg_latency = sum(health['latency']) / len(health['latency']) if health['latency'] else float('inf')
124
+
125
+ # (يمكن إضافة منطق ترتيب أكثر تعقيداً هنا مستقبلاً)
126
+ healthy_endpoints.append((ep, avg_latency, health['consecutive_errors']))
127
+
128
+ # الترتيب: الأقل أخطاء متتالية، ثم الأقل زمن استجابة
129
+ healthy_endpoints.sort(key=lambda x: (x[2], x[1]))
130
+
131
+ # خلط بسيط للنقاط السليمة لمنع التحميل الزائد على نقطة واحدة
132
+ healthy_list = [ep[0] for ep in healthy_endpoints if ep[2] == 0]
133
+ random.shuffle(healthy_list)
134
+
135
+ unhealthy_list = [ep[0] for ep in healthy_endpoints if ep[2] > 0]
136
+
137
+ return healthy_list + unhealthy_list
138
+
139
+ def _update_health(self, network: str, endpoint: str, success: bool, latency: float):
140
+ """
141
+ "التعلم" - تحديث إحصائيات صحة نقطة RPC.
142
+ """
143
+ health = self.endpoint_health[network][endpoint]
144
+
145
+ if success:
146
+ health['latency'].append(latency)
147
+ health['consecutive_errors'] = 0
148
+ health['circuit_open'] = False
149
+ else:
150
+ health['consecutive_errors'] += 1
151
+ health['total_errors'] += 1
152
+ health['last_error_time'] = time.time()
153
+ if health['consecutive_errors'] >= RPC_ERROR_THRESHOLD:
154
+ health['circuit_open'] = True
155
+ print(f"🚨 [RPC Manager] قاطع الدائرة مفعل! إيقاف مؤقت لـ: {endpoint.split('//')[-1]}")
156
+
157
+ async def post(self, network: str, payload: dict, timeout: float = 20.0):
158
+ """
159
+ إرسال طلب POST إلى أفضل نقطة RPC متاحة للشبكة.
160
+ يعيد المحاولة تلقائياً عند الفشل.
161
+ """
162
+ endpoints = self._get_healthy_endpoints(network)
163
+ if not endpoints:
164
+ print(f"❌ [RPC Manager] لا توجد نقاط RPC متاحة أو سليمة لشبكة {network}")
165
+ return None
166
+
167
+ # محاولة أفضل 3 نقاط متاحة
168
+ for endpoint in endpoints[:3]:
169
+ start_time = time.time()
170
+ ep_name = endpoint.split('//')[-1].split('/')[0] # للاختصار
171
+
172
+ try:
173
+ async with self.rpc_semaphore:
174
+ response = await self.http_client.post(endpoint, json=payload, timeout=timeout)
175
+ response.raise_for_status() # يطلق استثناء لأخطاء 4xx/5xx
176
+
177
+ latency = time.time() - start_time
178
+ self._update_health(network, endpoint, success=True, latency=latency)
179
+
180
+ print(f"✅ [RPC] {network} ({ep_name}) - {latency:.2f}s")
181
+ return response.json()
182
+
183
+ except (httpx.HTTPStatusError, httpx.RequestError, ssl.SSLError, asyncio.TimeoutError, json.JSONDecodeError) as e:
184
+ latency = time.time() - start_time
185
+ self._update_health(network, endpoint, success=False, latency=latency)
186
+ print(f"⚠️ [RPC] فشل {network} ({ep_name}): {type(e).__name__}")
187
+ continue # انتقل إلى النقطة التالية
188
+ except Exception as e:
189
+ latency = time.time() - start_time
190
+ self._update_health(network, endpoint, success=False, latency=latency)
191
+ print(f"❌ [RPC] فشل فادح {network} ({ep_name}): {e}")
192
+ continue # انتقل إلى النقطة التالية
193
+
194
+ print(f"❌ [RPC Manager] فشلت جميع المحاولات لشبكة {network} للطلب: {payload.get('method', 'N/A')}")
195
+ return None
196
+
197
+ async def get(self, base_url: str, params: dict, headers: dict = None, timeout: float = 15.0, use_coingecko_semaphore: bool = False):
198
+ """
199
+ إرسال طلب GET (للمستكشفات أو CoinGecko).
200
+ يدير حدود الطلبات بذكاء.
201
+ """
202
+ semaphore = self.coingecko_semaphore if use_coingecko_semaphore else self.rpc_semaphore
203
+
204
+ try:
205
+ async with semaphore:
206
+ response = await self.http_client.get(base_url, params=params, headers=headers, timeout=timeout)
207
+
208
+ if response.status_code == 429: # Too Many Requests
209
+ print(f"⚠️ [GET] خطأ 429 (Rate Limit) من {base_url}. الانتظار 5 ثوان...")
210
+ await asyncio.sleep(5)
211
+ # إعادة المحاولة مرة واحدة
212
+ response = await self.http_client.get(base_url, params=params, headers=headers, timeout=timeout)
213
+
214
+ response.raise_for_status()
215
+
216
+ return response.json()
217
+
218
+ except httpx.HTTPStatusError as e:
219
+ print(f"❌ [GET] خطأ HTTP من {base_url}: {e.response.status_code}")
220
+ return None
221
+ except (httpx.RequestError, asyncio.TimeoutError) as e:
222
+ print(f"❌ [GET] خطأ اتصال/مهلة من {base_url}: {e}")
223
+ return None
224
+ except json.JSONDecodeError as e:
225
+ print(f"❌ [GET] خطأ JSON من {base_url}: {e}")
226
+ return None
227
+ except Exception as e:
228
+ print(f"❌ [GET] خطأ غير متوقع من {base_url}: {e}")
229
+ return None