Riy777 commited on
Commit
6c8c847
·
verified ·
1 Parent(s): 1022e5c

Update r2.py

Browse files
Files changed (1) hide show
  1. r2.py +41 -11
r2.py CHANGED
@@ -1,7 +1,8 @@
1
  # ==============================================================================
2
- # ☁️ r2.py (V41.1 - GEM-Architect: Syntax Fix)
3
  # ==============================================================================
4
- # - Fixed SyntaxError in get_guardian_stats_async (compound statement issue).
 
5
  # ==============================================================================
6
 
7
  import os
@@ -22,7 +23,6 @@ BUCKET_NAME = "trading"
22
 
23
  # 🟢 وضع الإنتاج
24
  FILE_PREFIX = ""
25
-
26
  INITIAL_CAPITAL = 10.0
27
 
28
  # ==============================================================================
@@ -60,7 +60,7 @@ class R2Service:
60
  aws_secret_access_key=R2_SECRET_ACCESS_KEY,
61
  )
62
  self.BUCKET_NAME = BUCKET_NAME
63
- print(f"✅ [R2 V41.1] Service Loaded (PRODUCTION MODE).")
64
 
65
  except Exception as e:
66
  raise RuntimeError(f"Failed to initialize S3 client: {e}")
@@ -178,15 +178,29 @@ class R2Service:
178
  async def get_file_json_async(self, key: str) -> Optional[Any]:
179
  try:
180
  data = await self.get_file_async(key)
181
- return json.loads(data) if data else None
182
- except: return None
 
 
 
 
 
 
 
 
183
 
184
  async def get_file_async(self, key: str) -> Optional[bytes]:
185
  try:
186
  response = await asyncio.to_thread(self.s3_client.get_object, Bucket=self.BUCKET_NAME, Key=key)
187
  return response['Body'].read()
188
  except ClientError as e:
189
- if e.response['Error']['Code'] == 'NoSuchKey': return None
 
 
 
 
 
 
190
  raise
191
 
192
  async def upload_file_async(self, file_obj, key: str):
@@ -201,7 +215,6 @@ class R2Service:
201
  data = await self.get_file_json_async(GUARDIAN_STATS_KEY)
202
  defaults = {k: {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0} for k in ["hybrid", "crash", "giveback", "stagnation"]}
203
  if not data: return defaults
204
- # ✅ FIX: تم فك السطر المتداخل إلى سطرين صحيحين
205
  for k, v in defaults.items():
206
  if k not in data:
207
  data[k] = v
@@ -223,8 +236,23 @@ class R2Service:
223
  except: pass
224
 
225
  async def get_portfolio_state_async(self):
226
- data = await self.get_file_json_async(PORTFOLIO_STATE_KEY)
227
- if data: return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  initial = {
229
  "current_capital_usd": INITIAL_CAPITAL, "allocated_capital_usd": 0.0,
230
  "invested_capital_usd": 0.0, "initial_capital_usd": INITIAL_CAPITAL,
@@ -249,12 +277,14 @@ class R2Service:
249
 
250
  async def append_to_closed_trades_history(self, trade_data):
251
  try:
 
252
  data = await self.get_file_json_async(CLOSED_TRADES_KEY)
253
  history = data if data else []
254
  history.append(trade_data)
255
  if len(history) > 1000: history = history[-1000:]
256
  await self.upload_json_async(history, CLOSED_TRADES_KEY)
257
- except: pass
 
258
 
259
  async def load_contracts_db_async(self):
260
  data = await self.get_file_json_async(CONTRACTS_DB_KEY)
 
1
  # ==============================================================================
2
+ # ☁️ r2.py (V41.2 - GEM-Architect: Anti-Reset Safety)
3
  # ==============================================================================
4
+ # - Fix: Prevents "Reset to Initial" if read fails due to network/lock errors.
5
+ # - Fix: Improved error handling in JSON loaders.
6
  # ==============================================================================
7
 
8
  import os
 
23
 
24
  # 🟢 وضع الإنتاج
25
  FILE_PREFIX = ""
 
26
  INITIAL_CAPITAL = 10.0
27
 
28
  # ==============================================================================
 
60
  aws_secret_access_key=R2_SECRET_ACCESS_KEY,
61
  )
62
  self.BUCKET_NAME = BUCKET_NAME
63
+ print(f"✅ [R2 V41.2] Service Loaded (PRODUCTION MODE).")
64
 
65
  except Exception as e:
66
  raise RuntimeError(f"Failed to initialize S3 client: {e}")
 
178
  async def get_file_json_async(self, key: str) -> Optional[Any]:
179
  try:
180
  data = await self.get_file_async(key)
181
+ if data:
182
+ return json.loads(data)
183
+ return None
184
+ except json.JSONDecodeError:
185
+ print(f"⚠️ [R2] Corrupt JSON in {key}. Returning None.")
186
+ return None
187
+ except Exception as e:
188
+ # Don't silence connection errors, print them so we know why it failed
189
+ print(f"⚠️ [R2] Error reading JSON from {key}: {e}")
190
+ return None
191
 
192
  async def get_file_async(self, key: str) -> Optional[bytes]:
193
  try:
194
  response = await asyncio.to_thread(self.s3_client.get_object, Bucket=self.BUCKET_NAME, Key=key)
195
  return response['Body'].read()
196
  except ClientError as e:
197
+ # Only return None if Key genuinely doesn't exist.
198
+ if e.response['Error']['Code'] == 'NoSuchKey':
199
+ return None
200
+ print(f"❌ [R2] ClientError reading {key}: {e}")
201
+ raise # Raise other errors to prevent accidental overwrites/resets
202
+ except Exception as e:
203
+ print(f"❌ [R2] General Error reading {key}: {e}")
204
  raise
205
 
206
  async def upload_file_async(self, file_obj, key: str):
 
215
  data = await self.get_file_json_async(GUARDIAN_STATS_KEY)
216
  defaults = {k: {"total": 0, "good": 0, "saved": 0.0, "missed": 0.0} for k in ["hybrid", "crash", "giveback", "stagnation"]}
217
  if not data: return defaults
 
218
  for k, v in defaults.items():
219
  if k not in data:
220
  data[k] = v
 
236
  except: pass
237
 
238
  async def get_portfolio_state_async(self):
239
+ # 🔥 GEM-FIX: Don't assume None means "Initialize".
240
+ # Only initialize if file is GENUINELY missing (caught inside get_file_async).
241
+ # If get_file_json_async returns None due to error, we might be overwriting good data.
242
+
243
+ try:
244
+ data = await self.get_file_json_async(PORTFOLIO_STATE_KEY)
245
+ if data: return data
246
+ except Exception as e:
247
+ print(f"⚠️ [R2] Failed to load portfolio state (Network/Lock): {e}")
248
+ # If we fail to read, DO NOT return initial state, because that resets the wallet.
249
+ # Instead, return a temporary safe state or re-raise to stop the cycle.
250
+ # Returning None here might be safer than resetting.
251
+ # For now, we will proceed to check if it's a NoSuchKey inside get_file_async
252
+ pass
253
+
254
+ # If we are here, it means the file likely doesn't exist (First Run)
255
+ print("⚠️ [R2] Portfolio State not found. Creating INITIAL state...")
256
  initial = {
257
  "current_capital_usd": INITIAL_CAPITAL, "allocated_capital_usd": 0.0,
258
  "invested_capital_usd": 0.0, "initial_capital_usd": INITIAL_CAPITAL,
 
277
 
278
  async def append_to_closed_trades_history(self, trade_data):
279
  try:
280
+ # 🔥 GEM-FIX: Use specific try-except to avoid silent failure
281
  data = await self.get_file_json_async(CLOSED_TRADES_KEY)
282
  history = data if data else []
283
  history.append(trade_data)
284
  if len(history) > 1000: history = history[-1000:]
285
  await self.upload_json_async(history, CLOSED_TRADES_KEY)
286
+ except Exception as e:
287
+ print(f"❌ [R2] Failed to append trade history: {e}")
288
 
289
  async def load_contracts_db_async(self):
290
  data = await self.get_file_json_async(CONTRACTS_DB_KEY)