Karan Adhikari commited on
Commit
f87315f
·
unverified ·
1 Parent(s): 35f46fa

Update custom_dl.py

Browse files
Files changed (1) hide show
  1. Backend/helper/custom_dl.py +102 -140
Backend/helper/custom_dl.py CHANGED
@@ -1,4 +1,6 @@
1
  import asyncio
 
 
2
  import time
3
  import secrets
4
  from collections import deque
@@ -16,45 +18,29 @@ from Backend import db
16
  from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
17
 
18
  ACTIVE_STREAMS: Dict[str, Dict] = {}
19
- RECENT_STREAMS = deque(maxlen=3)
20
 
21
 
22
  def get_adaptive_chunk_size(client_index: int) -> int:
23
- """Return the best chunk size (bytes) for this client based on recent speed.
24
-
25
- Speed tiers:
26
- < 5 MB/s → 1 MB (conservative, faster first-byte)
27
- 5-20 MB/s → 1 MB (default)
28
- 20-60 MB/s → 2 MB (fewer round-trips on fast sessions)
29
- > 60 MB/s → 4 MB (maximise throughput on very fast sessions)
30
- """
31
- speed = client_avg_mbps.get(client_index, 0.0)
32
- if speed >= 60:
33
- return 4 * 1024 * 1024
34
- if speed >= 20:
35
- return 2 * 1024 * 1024
36
- # Default to 1MB (increased from 512KB to reduce round-trips)
37
- return 1 * 1024 * 1024
38
-
39
 
40
  class ByteStreamer:
41
  CHUNK_SIZE = 1024 * 1024 # 1 MB
42
  CLEAN_INTERVAL = 30 * 60 # 30 minutes
43
- _instances: Dict[int, "ByteStreamer"] = {} # client_index → streamer (for fallback)
44
 
45
  def __init__(self, client: Client, client_index: int = -1):
46
  self.client = client
47
  self.client_index = client_index
48
  self._file_id_cache: Dict[int, FileId] = {}
49
  self._session_lock = asyncio.Lock()
50
- # Register this streamer so fallback logic can reuse it
51
  if client_index >= 0:
52
  ByteStreamer._instances[client_index] = self
53
  asyncio.create_task(self._clean_cache())
54
  asyncio.create_task(self._prewarm_sessions())
55
 
56
  async def _prewarm_sessions(self):
57
- common_dcs = [1, 2, 4, 5] # Main Telegram DCs
58
  LOGGER.debug("Pre-warming media sessions for common DCs...")
59
 
60
  for dc in common_dcs:
@@ -114,32 +100,6 @@ class ByteStreamer:
114
  self._file_id_cache[message_id] = file_id
115
  return self._file_id_cache[message_id]
116
 
117
- def _get_best_fallback_client(self, client_index: int, target_dc: int) -> Optional[int]:
118
- """Select best fallback client: prefer DC-local, avoid high-failure clients."""
119
- def _score(idx: int) -> int:
120
- # Heavy penalty (1000×) for clients with 3+ failures
121
- if client_failures.get(idx, 0) >= 3:
122
- return 10000
123
- # Penalize by failure count + workload
124
- return (client_failures.get(idx, 0) * 50) + work_loads.get(idx, 0)
125
-
126
- # Tier 1: DC-local clients (prefer same DC)
127
- dc_local = [
128
- idx for idx in multi_clients.keys()
129
- if idx != client_index and client_dc_map.get(idx) == target_dc
130
- ]
131
- if dc_local:
132
- best = min(dc_local, key=_score)
133
- return best if _score(best) < 5000 else None
134
-
135
- # Tier 2: Any available client (excluding primary)
136
- other_clients = [idx for idx in multi_clients.keys() if idx != client_index]
137
- if other_clients:
138
- best = min(other_clients, key=_score)
139
- return best if _score(best) < 5000 else None
140
-
141
- return None
142
-
143
  async def prefetch_stream(
144
  self,
145
  file_id: FileId,
@@ -154,6 +114,9 @@ class ByteStreamer:
154
  meta: Optional[dict] = None,
155
  parallelism: int = 2,
156
  request: Optional[Request] = None,
 
 
 
157
  ):
158
  if not stream_id:
159
  stream_id = secrets.token_hex(8)
@@ -186,106 +149,103 @@ class ByteStreamer:
186
  stop_event = asyncio.Event()
187
 
188
  media_session = await self._get_media_session(file_id)
189
- location = await self._get_location(file_id)
190
- target_dc = file_id.dc_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
193
- """Fetch one chunk with timeout, exponential back-off, and smart fallback.
 
194
 
195
- Retry schedule (max 4 tries):
196
- try 0 → primary client / session, 20 s timeout
197
- try 1-2 → best fallback client (DC-local preferred), 20 s timeout
198
- try 3 → any available fallback, 20 s timeout
199
-
200
- Increments failure counter on timeout so select_best_client() deprioritizes
201
- hammered clients.
202
- """
203
  tries = 0
204
- MAX_RETRIES = 4 # Increased from 3 to 4 for better resilience
205
- TIMEOUT_SEC = 20.0 # Increased from 15s to 20s for cross-DC jitter
206
-
207
- while tries < MAX_RETRIES and not stop_event.is_set():
208
- # --- choose which media session to use this attempt ---
209
- use_session = media_session
210
- use_client_idx = client_index
211
-
212
- if tries >= 1 and len(multi_clients) > 1:
213
- # Smart fallback: pick best other client (DC-aware)
214
- fallback_idx = self._get_best_fallback_client(client_index, target_dc)
215
- if fallback_idx is not None:
216
- fb_streamer = ByteStreamer._instances.get(fallback_idx)
217
- if fb_streamer is None:
218
- fb_streamer = ByteStreamer(multi_clients[fallback_idx], fallback_idx)
219
- try:
220
- use_session = await fb_streamer._get_media_session(file_id)
221
- use_client_idx = fallback_idx
222
- LOGGER.debug(
223
- "Chunk fallback: seq=%s try=%s primary=%s (DC%s) → fallback=%s (DC%s)",
224
- seq_idx, tries, client_index, client_dc_map.get(client_index, "?"),
225
- fallback_idx, client_dc_map.get(fallback_idx, "?"),
226
- )
227
- except Exception as e:
228
- LOGGER.debug(f"Fallback session creation failed: {e}, retrying with primary")
229
- use_session = media_session # revert if fallback session fails
230
- use_client_idx = client_index
231
-
232
- # --- attempt the fetch with a hard timeout ---
233
  try:
234
  r = await asyncio.wait_for(
235
- use_session.send(
236
  raw.functions.upload.GetFile(
237
- location=location, offset=off, limit=chunk_size
238
  )
239
  ),
240
- timeout=TIMEOUT_SEC,
241
  )
242
  chunk_bytes = getattr(r, "bytes", None) if r else None
243
-
244
  if chunk_bytes == b"":
245
- # Empty chunk = EOF (legitimate)
246
  return seq_idx, None
247
 
248
- if chunk_bytes is None:
249
- # None from server = real error, retry
250
- tries += 1
251
- LOGGER.debug(
252
- "Chunk returned None seq=%s off=%s try=%s client=%s, retrying",
253
- seq_idx, off, tries, use_client_idx,
254
- )
255
- continue
256
-
257
- # If we succeeded via a fallback, mark primary as degraded
258
- if use_client_idx != client_index:
259
- client_failures[client_index] = client_failures.get(client_index, 0) + 1
260
- LOGGER.debug("Primary client degraded (used fallback); failures=%s",
261
- client_failures[client_index])
262
-
263
  return seq_idx, chunk_bytes
264
 
265
  except asyncio.TimeoutError:
266
  tries += 1
267
- client_failures[use_client_idx] = client_failures.get(use_client_idx, 0) + 1
268
  LOGGER.warning(
269
- "Chunk timeout seq=%s off=%s try=%s client=%s (failures=%s), retrying...",
270
- seq_idx, off, tries, use_client_idx, client_failures[use_client_idx],
271
  )
272
- if tries < MAX_RETRIES:
273
- # Exponential back-off: 0.5, 1, 2, 4 seconds (cap at 10)
274
- await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
275
-
276
  except Exception as e:
277
- tries += 1
278
- LOGGER.debug(
279
- "Fetch chunk error seq=%s off=%s try=%s client=%s err=%s",
280
- seq_idx, off, tries, use_client_idx, getattr(e, "args", e),
281
- )
282
- if tries < MAX_RETRIES:
283
- await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
- # All retries exhausted
286
  LOGGER.error(
287
- "Failed to fetch chunk seq=%s off=%s after %d retries, client=%s (failures=%s)",
288
- seq_idx, off, MAX_RETRIES, client_index, client_failures.get(client_index, 0),
289
  )
290
  return seq_idx, None
291
 
@@ -337,12 +297,7 @@ class ByteStreamer:
337
  scheduled_tasks.pop(completed_seq, None)
338
 
339
  if chunk_bytes is None:
340
- # Failed to fetch after all retries: terminate stream cleanly
341
- LOGGER.error(
342
- "Chunk permanently failed for stream=%s seq=%s. Terminating stream.",
343
- stream_id, seq_idx
344
- )
345
- ACTIVE_STREAMS[stream_id]["status"] = "error"
346
  await q.put((None, None))
347
  return
348
 
@@ -386,18 +341,28 @@ class ByteStreamer:
386
  async def consumer_generator():
387
  producer_task = asyncio.create_task(producer())
388
  current_part_idx = 1
 
389
 
390
  try:
391
  while True:
 
 
 
 
 
 
 
 
 
 
392
  try:
393
- if request and await request.is_disconnected():
394
- LOGGER.debug("Client disconnected for stream %s; cancelling stream", stream_id)
395
- ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
396
- break
397
- except Exception:
398
- pass
399
 
400
- off_chunk = await q.get()
401
  if off_chunk is None:
402
  break
403
 
@@ -460,7 +425,6 @@ class ByteStreamer:
460
  ACTIVE_STREAMS[stream_id]["status"] = "error"
461
  if not producer_task.done():
462
  producer_task.cancel()
463
- raise
464
  finally:
465
  if not producer_task.done():
466
  try:
@@ -485,13 +449,11 @@ class ByteStreamer:
485
  "parallelism": parallelism,
486
  })
487
 
488
- # --- Update rolling average speed for this client ---
489
  prev = client_avg_mbps.get(client_index, 0.0)
490
  if prev == 0.0:
491
  client_avg_mbps[client_index] = avg_mbps
492
  else:
493
- # Exponential moving average: 30% new, 70% history
494
- client_avg_mbps[client_index] = 0.7 * prev + 0.3 * avg_mbps
495
 
496
  # --- Log Analytics to DB ---
497
  entry["chunk_size"] = chunk_size
 
1
  import asyncio
2
+ import random
3
+ import re
4
  import time
5
  import secrets
6
  from collections import deque
 
18
  from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
19
 
20
  ACTIVE_STREAMS: Dict[str, Dict] = {}
21
+ RECENT_STREAMS = deque(maxlen=50)
22
 
23
 
24
  def get_adaptive_chunk_size(client_index: int) -> int:
25
+ return 1024 * 1024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  class ByteStreamer:
28
  CHUNK_SIZE = 1024 * 1024 # 1 MB
29
  CLEAN_INTERVAL = 30 * 60 # 30 minutes
30
+ _instances: Dict[int, "ByteStreamer"] = {}
31
 
32
  def __init__(self, client: Client, client_index: int = -1):
33
  self.client = client
34
  self.client_index = client_index
35
  self._file_id_cache: Dict[int, FileId] = {}
36
  self._session_lock = asyncio.Lock()
 
37
  if client_index >= 0:
38
  ByteStreamer._instances[client_index] = self
39
  asyncio.create_task(self._clean_cache())
40
  asyncio.create_task(self._prewarm_sessions())
41
 
42
  async def _prewarm_sessions(self):
43
+ common_dcs = [1, 2, 4, 5]
44
  LOGGER.debug("Pre-warming media sessions for common DCs...")
45
 
46
  for dc in common_dcs:
 
100
  self._file_id_cache[message_id] = file_id
101
  return self._file_id_cache[message_id]
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  async def prefetch_stream(
104
  self,
105
  file_id: FileId,
 
114
  meta: Optional[dict] = None,
115
  parallelism: int = 2,
116
  request: Optional[Request] = None,
117
+ chat_id: Optional[int] = None,
118
+ message_id: Optional[int] = None,
119
+ extra_clients: Optional[List] = None,
120
  ):
121
  if not stream_id:
122
  stream_id = secrets.token_hex(8)
 
149
  stop_event = asyncio.Event()
150
 
151
  media_session = await self._get_media_session(file_id)
152
+ location_box: List[object] = [await self._get_location(file_id)]
153
+ async def _make_refresh_fn(loc_b, streamer_ref, file_id_ref):
154
+ async def _refresh() -> bool:
155
+ if not chat_id or not message_id:
156
+ return False
157
+ try:
158
+ streamer_ref._file_id_cache.pop(message_id, None)
159
+ fresh = await get_file_ids(streamer_ref.client, chat_id, message_id)
160
+ if fresh:
161
+ streamer_ref._file_id_cache[message_id] = fresh
162
+ loc_b[0] = await ByteStreamer._get_location(fresh)
163
+ LOGGER.info("Refreshed file location for msg_id=%s", message_id)
164
+ return True
165
+ except Exception as exc:
166
+ LOGGER.warning("Location refresh failed for msg_id=%s: %s", message_id, exc)
167
+ return False
168
+ return _refresh
169
+
170
+ primary_refresh = await _make_refresh_fn(location_box, self, file_id)
171
+ session_pool = [(client_index, media_session, location_box, primary_refresh)]
172
+
173
+ if extra_clients:
174
+ for ec_idx, ec_streamer, ec_file_id in extra_clients:
175
+ try:
176
+ ec_session = await ec_streamer._get_media_session(ec_file_id)
177
+ ec_loc_box = [await ByteStreamer._get_location(ec_file_id)]
178
+ ec_refresh = await _make_refresh_fn(ec_loc_box, ec_streamer, ec_file_id)
179
+ session_pool.append((ec_idx, ec_session, ec_loc_box, ec_refresh))
180
+ except Exception as e:
181
+ LOGGER.warning("Skipping extra client %s (session setup failed): %s", ec_idx, e)
182
 
183
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
184
+ slot = seq_idx % len(session_pool)
185
+ c_idx, c_session, c_loc_box, c_refresh = session_pool[slot]
186
 
 
 
 
 
 
 
 
 
187
  tries = 0
188
+ flood_tries = 0
189
+ while tries < 3 and flood_tries < 5 and not stop_event.is_set():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  try:
191
  r = await asyncio.wait_for(
192
+ c_session.send(
193
  raw.functions.upload.GetFile(
194
+ location=c_loc_box[0], offset=off, limit=chunk_size
195
  )
196
  ),
197
+ timeout=15.0,
198
  )
199
  chunk_bytes = getattr(r, "bytes", None) if r else None
200
+
201
  if chunk_bytes == b"":
 
202
  return seq_idx, None
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  return seq_idx, chunk_bytes
205
 
206
  except asyncio.TimeoutError:
207
  tries += 1
208
+ client_failures[c_idx] = client_failures.get(c_idx, 0) + 1
209
  LOGGER.warning(
210
+ "Chunk timeout seq=%s off=%s try=%s client=%s",
211
+ seq_idx, off, tries, c_idx,
212
  )
213
+ await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
214
+
 
 
215
  except Exception as e:
216
+ err_str = str(e)
217
+
218
+ if "FILE_REFERENCE" in err_str or "file_reference" in err_str.lower():
219
+ LOGGER.warning(
220
+ "FILE_REFERENCE_EXPIRED seq=%s off=%s client=%s — refreshing",
221
+ seq_idx, off, c_idx,
222
+ )
223
+ await c_refresh()
224
+
225
+ flood_m = re.search(r'wait of (\d+) second', err_str, re.IGNORECASE)
226
+ if flood_m:
227
+ required = float(flood_m.group(1))
228
+ jitter = random.uniform(0.5, 2.0)
229
+ wait = required + jitter
230
+ flood_tries += 1
231
+ LOGGER.warning(
232
+ "FloodWait %ds seq=%s off=%s client=%s "
233
+ "(flood_try=%s/5) — sleeping %.1fs",
234
+ int(required), seq_idx, off, c_idx, flood_tries, wait,
235
+ )
236
+ await asyncio.sleep(wait)
237
+ else:
238
+ tries += 1
239
+ backoff = min(0.5 * (2 ** (tries - 1)), 10.0)
240
+ LOGGER.warning(
241
+ "Chunk error seq=%s off=%s try=%s client=%s (backoff=%.1fs): %s",
242
+ seq_idx, off, tries, c_idx, backoff, err_str,
243
+ )
244
+ await asyncio.sleep(backoff)
245
 
 
246
  LOGGER.error(
247
+ "Failed to fetch chunk seq=%s off=%s after %s tries + %s flood waits, client=%s",
248
+ seq_idx, off, tries, flood_tries, c_idx,
249
  )
250
  return seq_idx, None
251
 
 
297
  scheduled_tasks.pop(completed_seq, None)
298
 
299
  if chunk_bytes is None:
300
+ LOGGER.error("Chunk fetch failed for stream=%s seq=%s — aborting stream.", stream_id, seq_idx)
 
 
 
 
 
301
  await q.put((None, None))
302
  return
303
 
 
341
  async def consumer_generator():
342
  producer_task = asyncio.create_task(producer())
343
  current_part_idx = 1
344
+ _disconnect_check_counter = 0
345
 
346
  try:
347
  while True:
348
+ _disconnect_check_counter += 1
349
+ if _disconnect_check_counter % 8 == 0:
350
+ try:
351
+ if request and await request.is_disconnected():
352
+ LOGGER.debug("Client disconnected for stream %s; cancelling stream", stream_id)
353
+ ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
354
+ break
355
+ except Exception:
356
+ pass
357
+
358
  try:
359
+ # Max chunk time: 3 retries × 15 s + backoff ≈ 48 s → use 90 s
360
+ off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
361
+ except asyncio.TimeoutError:
362
+ LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
363
+ ACTIVE_STREAMS[stream_id]["status"] = "error"
364
+ break
365
 
 
366
  if off_chunk is None:
367
  break
368
 
 
425
  ACTIVE_STREAMS[stream_id]["status"] = "error"
426
  if not producer_task.done():
427
  producer_task.cancel()
 
428
  finally:
429
  if not producer_task.done():
430
  try:
 
449
  "parallelism": parallelism,
450
  })
451
 
 
452
  prev = client_avg_mbps.get(client_index, 0.0)
453
  if prev == 0.0:
454
  client_avg_mbps[client_index] = avg_mbps
455
  else:
456
+ client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps
 
457
 
458
  # --- Log Analytics to DB ---
459
  entry["chunk_size"] = chunk_size