Karan Adhikari commited on
Commit
2c766ea
·
unverified ·
1 Parent(s): 7bb00b9

Update custom_dl.py

Browse files
Files changed (1) hide show
  1. Backend/helper/custom_dl.py +6 -101
Backend/helper/custom_dl.py CHANGED
@@ -87,10 +87,10 @@ class ByteStreamer:
87
  last_part_cut: int,
88
  part_count: int,
89
  chunk_size: int,
90
- prefetch: int = 3,
91
  stream_id: Optional[str] = None,
92
  meta: Optional[dict] = None,
93
- parallelism: int = 2,
94
  request: Optional[Request] = None,
95
  chat_id: Optional[int] = None,
96
  message_id: Optional[int] = None,
@@ -138,7 +138,6 @@ class ByteStreamer:
138
  if fresh:
139
  streamer_ref._file_id_cache[message_id] = fresh
140
  loc_b[0] = await ByteStreamer._get_location(fresh)
141
- LOGGER.info("Refreshed file location for msg_id=%s", message_id)
142
  return True
143
  except Exception as exc:
144
  LOGGER.warning("Location refresh failed for msg_id=%s: %s", message_id, exc)
@@ -184,20 +183,12 @@ class ByteStreamer:
184
  except asyncio.TimeoutError:
185
  tries += 1
186
  client_failures[c_idx] = client_failures.get(c_idx, 0) + 1
187
- LOGGER.warning(
188
- "Chunk timeout seq=%s off=%s try=%s client=%s",
189
- seq_idx, off, tries, c_idx,
190
- )
191
  await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
192
 
193
  except Exception as e:
194
  err_str = str(e)
195
 
196
  if "FILE_REFERENCE" in err_str or "file_reference" in err_str.lower():
197
- LOGGER.warning(
198
- "FILE_REFERENCE_EXPIRED seq=%s off=%s client=%s — refreshing",
199
- seq_idx, off, c_idx,
200
- )
201
  await c_refresh()
202
 
203
  flood_m = re.search(r'wait of (\d+) second', err_str, re.IGNORECASE)
@@ -206,25 +197,11 @@ class ByteStreamer:
206
  jitter = random.uniform(0.5, 2.0)
207
  wait = required + jitter
208
  flood_tries += 1
209
- LOGGER.warning(
210
- "FloodWait %ds seq=%s off=%s client=%s "
211
- "(flood_try=%s/5) — sleeping %.1fs",
212
- int(required), seq_idx, off, c_idx, flood_tries, wait,
213
- )
214
  await asyncio.sleep(wait)
215
  else:
216
  tries += 1
217
  backoff = min(0.5 * (2 ** (tries - 1)), 10.0)
218
- LOGGER.warning(
219
- "Chunk error seq=%s off=%s try=%s client=%s (backoff=%.1fs): %s",
220
- seq_idx, off, tries, c_idx, backoff, err_str,
221
- )
222
  await asyncio.sleep(backoff)
223
-
224
- LOGGER.error(
225
- "Failed to fetch chunk seq=%s off=%s after %s tries + %s flood waits, client=%s",
226
- seq_idx, off, tries, flood_tries, c_idx,
227
- )
228
  return seq_idx, None
229
 
230
  async def producer():
@@ -275,7 +252,6 @@ class ByteStreamer:
275
  scheduled_tasks.pop(completed_seq, None)
276
 
277
  if chunk_bytes is None:
278
- LOGGER.error("Chunk fetch failed for stream=%s seq=%s — aborting stream.", stream_id, seq_idx)
279
  await q.put((None, None))
280
  return
281
 
@@ -303,7 +279,6 @@ class ByteStreamer:
303
  await q.put((None, None))
304
 
305
  except asyncio.CancelledError:
306
- LOGGER.debug("Producer cancelled for stream %s", stream_id)
307
  try:
308
  await q.put((None, None))
309
  except Exception:
@@ -327,14 +302,12 @@ class ByteStreamer:
327
  if _disconnect_check_counter % 8 == 0:
328
  try:
329
  if request and await request.is_disconnected():
330
- LOGGER.debug("Client disconnected for stream %s; cancelling stream", stream_id)
331
  ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
332
  break
333
  except Exception:
334
  pass
335
 
336
  try:
337
- # Max chunk time: 3 retries × 15 s + backoff ≈ 48 s → use 90 s
338
  off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
339
  except asyncio.TimeoutError:
340
  LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
@@ -393,7 +366,6 @@ class ByteStreamer:
393
  current_part_idx += 1
394
 
395
  except asyncio.CancelledError:
396
- LOGGER.debug("Consumer cancelled for stream %s", stream_id)
397
  if not producer_task.done():
398
  producer_task.cancel()
399
  ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
@@ -433,7 +405,6 @@ class ByteStreamer:
433
  else:
434
  client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps
435
 
436
- # --- Log Analytics to DB ---
437
  entry["chunk_size"] = chunk_size
438
  asyncio.create_task(db.log_stream_stats(entry))
439
 
@@ -490,49 +461,17 @@ class ByteStreamer:
490
  await session.send(raw.functions.auth.ImportAuthorization(id=exported.id, bytes=exported.bytes))
491
  break
492
  except AuthBytesInvalid:
493
- LOGGER.debug("AuthBytesInvalid during media session import; retrying...")
494
  await asyncio.sleep(0.5)
495
  except OSError:
496
- LOGGER.debug("OSError during media session import; retrying...")
497
  await asyncio.sleep(1)
498
 
499
  self.client.media_sessions[dc] = session
500
- LOGGER.debug("Created media session for DC %s", dc)
501
  return session
502
 
503
  @staticmethod
504
  async def _get_location(file_id: FileId) -> Union[
505
- raw.types.InputPhotoFileLocation,
506
  raw.types.InputDocumentFileLocation,
507
- raw.types.InputPeerPhotoFileLocation,
508
  ]:
509
- ftype = file_id.file_type
510
-
511
- if ftype == FileType.CHAT_PHOTO:
512
- if file_id.chat_id > 0:
513
- peer = raw.types.InputPeerUser(user_id=file_id.chat_id, access_hash=file_id.chat_access_hash)
514
- else:
515
- if file_id.chat_access_hash == 0:
516
- peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
517
- else:
518
- peer = raw.types.InputPeerChannel(channel_id=utils.get_channel_id(file_id.chat_id),
519
- access_hash=file_id.chat_access_hash)
520
-
521
- return raw.types.InputPeerPhotoFileLocation(
522
- peer=peer,
523
- volume_id=file_id.volume_id,
524
- local_id=file_id.local_id,
525
- big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG,
526
- )
527
-
528
- if ftype == FileType.PHOTO:
529
- return raw.types.InputPhotoFileLocation(
530
- id=file_id.media_id,
531
- access_hash=file_id.access_hash,
532
- file_reference=file_id.file_reference,
533
- thumb_size=file_id.thumbnail_size,
534
- )
535
-
536
  return raw.types.InputDocumentFileLocation(
537
  id=file_id.media_id,
538
  access_hash=file_id.access_hash,
@@ -551,7 +490,7 @@ class ByteStreamer:
551
  # Speed Test helper – runs independently, on-demand per file
552
  # ---------------------------------------------------------------------------
553
 
554
- TEST_CHUNK_SIZE = 100 * 1024 * 1024 # 100 MB per test download
555
 
556
 
557
  async def _speed_test_single_client(
@@ -561,11 +500,6 @@ async def _speed_test_single_client(
561
  message_id: int,
562
  progress_callback=None,
563
  ) -> dict:
564
- """
565
- Benchmark one client: fetch a FRESH FileId (file reference is per-session),
566
- then measure ping (time-to-first-byte) and download throughput for
567
- TEST_CHUNK_SIZE bytes of the target file.
568
- """
569
  dc_id = client_dc_map.get(client_index, "?")
570
  result = {
571
  "client_index": client_index,
@@ -577,15 +511,11 @@ async def _speed_test_single_client(
577
  "error": None,
578
  }
579
  try:
580
- # Each client MUST fetch its own FileId — file references are
581
- # per-session and will raise FILE_REFERENCE_EXPIRED if shared.
582
  streamer = ByteStreamer(client)
583
  file_id = await streamer.get_file_properties(chat_id, message_id)
584
 
585
  media_session = await streamer._get_media_session(file_id)
586
  location = await ByteStreamer._get_location(file_id)
587
-
588
- # --- Ping: time to first byte ---
589
  ping_start = time.perf_counter()
590
  tiny = await media_session.send(
591
  raw.functions.upload.GetFile(location=location, offset=0, limit=4096)
@@ -597,21 +527,15 @@ async def _speed_test_single_client(
597
  if not getattr(tiny, "bytes", None):
598
  result["error"] = "No data on ping probe"
599
  return result
600
-
601
- # --- Download: TEST_CHUNK_SIZE bytes with concurrency ---
602
  dl_start = time.perf_counter()
603
  last_progress_time = dl_start
604
  total_bytes = 0
605
-
606
- chunk_size = 512 * 1024 # 512 KB per request
607
- max_concurrent_chunks = 8 # Telegram caps around 8-10 connections/requests
608
-
609
  queue = asyncio.Queue()
610
- # Seed the queue with offsets from 0 to TEST_CHUNK_SIZE
611
  target_offsets = list(range(0, TEST_CHUNK_SIZE, chunk_size))
612
  for off in target_offsets:
613
  queue.put_nowait(off)
614
-
615
  eof_reached = False
616
 
617
  async def fetch_chunk_worker():
@@ -619,7 +543,6 @@ async def _speed_test_single_client(
619
  while not queue.empty() and not eof_reached:
620
  offset = queue.get_nowait()
621
  fetch_size = min(chunk_size, TEST_CHUNK_SIZE - offset)
622
-
623
  try:
624
  r = await asyncio.wait_for(
625
  media_session.send(
@@ -634,14 +557,10 @@ async def _speed_test_single_client(
634
  eof_reached = True
635
  queue.task_done()
636
  continue
637
-
638
  bytes_got = len(chunk)
639
  total_bytes += bytes_got
640
-
641
  if bytes_got < fetch_size:
642
- eof_reached = True # Natural EOF
643
-
644
- # Fire progress callback roughly every 1 second
645
  now = time.perf_counter()
646
  if progress_callback and (now - last_progress_time) >= 1.0:
647
  elapsed_so_far = now - dl_start
@@ -651,8 +570,6 @@ async def _speed_test_single_client(
651
  prog_res["bytes_downloaded"] = total_bytes
652
  prog_res["time_taken_sec"] = round(elapsed_so_far, 3)
653
  prog_res["speed_mbps"] = round(current_speed, 3)
654
-
655
- # Fire and forget callback (create_task) since we're in a worker
656
  if asyncio.iscoroutinefunction(progress_callback):
657
  asyncio.create_task(progress_callback(prog_res))
658
  else:
@@ -660,14 +577,11 @@ async def _speed_test_single_client(
660
  last_progress_time = now
661
 
662
  except asyncio.TimeoutError:
663
- # Expected during a speed probe — Telegram throttled or DC is slow.
664
- # Log at DEBUG so it doesn't pollute the production error log.
665
  LOGGER.debug(
666
  "Speed-test chunk timeout client=%s offset=%s (skipping)",
667
  client_index, offset,
668
  )
669
  except Exception as e:
670
- # Other transient errors (FloodWait, network blip, etc.)
671
  LOGGER.debug(
672
  "Speed-test fetch error client=%s offset=%s: %s",
673
  client_index, offset, e,
@@ -675,8 +589,6 @@ async def _speed_test_single_client(
675
 
676
  finally:
677
  queue.task_done()
678
-
679
- # Spawn workers
680
  workers = [
681
  asyncio.create_task(fetch_chunk_worker())
682
  for _ in range(max_concurrent_chunks)
@@ -704,13 +616,6 @@ async def _speed_test_single_client(
704
 
705
 
706
  async def run_speed_test(chat_id: int, message_id: int) -> List[dict]:
707
- """
708
- Run a parallel speed test against all active bot clients for the file
709
- identified by (chat_id, message_id).
710
-
711
- Each client fetches its own fresh FileId to avoid FILE_REFERENCE_EXPIRED.
712
- Returns a list of per-client result dicts sorted by speed descending.
713
- """
714
  if not multi_clients:
715
  return [{"error": "No bot clients connected"}]
716
 
 
87
  last_part_cut: int,
88
  part_count: int,
89
  chunk_size: int,
90
+ prefetch: int,
91
  stream_id: Optional[str] = None,
92
  meta: Optional[dict] = None,
93
+ parallelism: int,
94
  request: Optional[Request] = None,
95
  chat_id: Optional[int] = None,
96
  message_id: Optional[int] = None,
 
138
  if fresh:
139
  streamer_ref._file_id_cache[message_id] = fresh
140
  loc_b[0] = await ByteStreamer._get_location(fresh)
 
141
  return True
142
  except Exception as exc:
143
  LOGGER.warning("Location refresh failed for msg_id=%s: %s", message_id, exc)
 
183
  except asyncio.TimeoutError:
184
  tries += 1
185
  client_failures[c_idx] = client_failures.get(c_idx, 0) + 1
 
 
 
 
186
  await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
187
 
188
  except Exception as e:
189
  err_str = str(e)
190
 
191
  if "FILE_REFERENCE" in err_str or "file_reference" in err_str.lower():
 
 
 
 
192
  await c_refresh()
193
 
194
  flood_m = re.search(r'wait of (\d+) second', err_str, re.IGNORECASE)
 
197
  jitter = random.uniform(0.5, 2.0)
198
  wait = required + jitter
199
  flood_tries += 1
 
 
 
 
 
200
  await asyncio.sleep(wait)
201
  else:
202
  tries += 1
203
  backoff = min(0.5 * (2 ** (tries - 1)), 10.0)
 
 
 
 
204
  await asyncio.sleep(backoff)
 
 
 
 
 
205
  return seq_idx, None
206
 
207
  async def producer():
 
252
  scheduled_tasks.pop(completed_seq, None)
253
 
254
  if chunk_bytes is None:
 
255
  await q.put((None, None))
256
  return
257
 
 
279
  await q.put((None, None))
280
 
281
  except asyncio.CancelledError:
 
282
  try:
283
  await q.put((None, None))
284
  except Exception:
 
302
  if _disconnect_check_counter % 8 == 0:
303
  try:
304
  if request and await request.is_disconnected():
 
305
  ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
306
  break
307
  except Exception:
308
  pass
309
 
310
  try:
 
311
  off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
312
  except asyncio.TimeoutError:
313
  LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
 
366
  current_part_idx += 1
367
 
368
  except asyncio.CancelledError:
 
369
  if not producer_task.done():
370
  producer_task.cancel()
371
  ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
 
405
  else:
406
  client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps
407
 
 
408
  entry["chunk_size"] = chunk_size
409
  asyncio.create_task(db.log_stream_stats(entry))
410
 
 
461
  await session.send(raw.functions.auth.ImportAuthorization(id=exported.id, bytes=exported.bytes))
462
  break
463
  except AuthBytesInvalid:
 
464
  await asyncio.sleep(0.5)
465
  except OSError:
 
466
  await asyncio.sleep(1)
467
 
468
  self.client.media_sessions[dc] = session
 
469
  return session
470
 
471
  @staticmethod
472
  async def _get_location(file_id: FileId) -> Union[
 
473
  raw.types.InputDocumentFileLocation,
 
474
  ]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  return raw.types.InputDocumentFileLocation(
476
  id=file_id.media_id,
477
  access_hash=file_id.access_hash,
 
490
  # Speed Test helper – runs independently, on-demand per file
491
  # ---------------------------------------------------------------------------
492
 
493
+ TEST_CHUNK_SIZE = 100 * 1024 * 1024
494
 
495
 
496
  async def _speed_test_single_client(
 
500
  message_id: int,
501
  progress_callback=None,
502
  ) -> dict:
 
 
 
 
 
503
  dc_id = client_dc_map.get(client_index, "?")
504
  result = {
505
  "client_index": client_index,
 
511
  "error": None,
512
  }
513
  try:
 
 
514
  streamer = ByteStreamer(client)
515
  file_id = await streamer.get_file_properties(chat_id, message_id)
516
 
517
  media_session = await streamer._get_media_session(file_id)
518
  location = await ByteStreamer._get_location(file_id)
 
 
519
  ping_start = time.perf_counter()
520
  tiny = await media_session.send(
521
  raw.functions.upload.GetFile(location=location, offset=0, limit=4096)
 
527
  if not getattr(tiny, "bytes", None):
528
  result["error"] = "No data on ping probe"
529
  return result
 
 
530
  dl_start = time.perf_counter()
531
  last_progress_time = dl_start
532
  total_bytes = 0
533
+ chunk_size = 512 * 1024
534
+ max_concurrent_chunks = 8
 
 
535
  queue = asyncio.Queue()
 
536
  target_offsets = list(range(0, TEST_CHUNK_SIZE, chunk_size))
537
  for off in target_offsets:
538
  queue.put_nowait(off)
 
539
  eof_reached = False
540
 
541
  async def fetch_chunk_worker():
 
543
  while not queue.empty() and not eof_reached:
544
  offset = queue.get_nowait()
545
  fetch_size = min(chunk_size, TEST_CHUNK_SIZE - offset)
 
546
  try:
547
  r = await asyncio.wait_for(
548
  media_session.send(
 
557
  eof_reached = True
558
  queue.task_done()
559
  continue
 
560
  bytes_got = len(chunk)
561
  total_bytes += bytes_got
 
562
  if bytes_got < fetch_size:
563
+ eof_reached = True
 
 
564
  now = time.perf_counter()
565
  if progress_callback and (now - last_progress_time) >= 1.0:
566
  elapsed_so_far = now - dl_start
 
570
  prog_res["bytes_downloaded"] = total_bytes
571
  prog_res["time_taken_sec"] = round(elapsed_so_far, 3)
572
  prog_res["speed_mbps"] = round(current_speed, 3)
 
 
573
  if asyncio.iscoroutinefunction(progress_callback):
574
  asyncio.create_task(progress_callback(prog_res))
575
  else:
 
577
  last_progress_time = now
578
 
579
  except asyncio.TimeoutError:
 
 
580
  LOGGER.debug(
581
  "Speed-test chunk timeout client=%s offset=%s (skipping)",
582
  client_index, offset,
583
  )
584
  except Exception as e:
 
585
  LOGGER.debug(
586
  "Speed-test fetch error client=%s offset=%s: %s",
587
  client_index, offset, e,
 
589
 
590
  finally:
591
  queue.task_done()
 
 
592
  workers = [
593
  asyncio.create_task(fetch_chunk_worker())
594
  for _ in range(max_concurrent_chunks)
 
616
 
617
 
618
  async def run_speed_test(chat_id: int, message_id: int) -> List[dict]:
 
 
 
 
 
 
 
619
  if not multi_clients:
620
  return [{"error": "No bot clients connected"}]
621