Karan Adhikari commited on
Commit
14af9d0
·
unverified ·
1 Parent(s): f3b6a16

Revert "fixed chunk issue (#45)" (#46)

Browse files

This reverts commit f3b6a161a5007eab488f8ff69d055ef02405941d.

Backend/fastapi/routes/stream_routes.py CHANGED
@@ -91,24 +91,32 @@ def parse_range_header(range_header: str, file_size: int):
91
  def select_best_client(target_dc: int) -> int:
92
  """Pick the best available client.
93
 
94
- Prioritizes same-DC matches, but falls back to the healthiest global bot
95
- if no matching DC is found or all matching bots are overloaded.
 
 
 
96
  """
97
  def _score(idx: int) -> int:
98
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
99
 
100
- # --- DC-aware selection ---
101
  matching = [
102
  idx for idx, dc in client_dc_map.items()
103
  if dc == target_dc and idx in multi_clients
104
  ]
105
  if matching:
106
  selected = min(matching, key=_score)
 
107
  return selected
 
108
 
109
- # Fallback to healthiest global bot
110
  if multi_clients:
111
  selected = min(multi_clients.keys(), key=_score)
 
 
 
 
112
  return selected
113
 
114
  return 0
@@ -255,22 +263,14 @@ async def media_streamer(
255
  from Backend.pyrofork.bot import work_loads, client_failures
256
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
257
 
258
- # Multi-connection striping: Use ALL available bots to maximize speed,
259
- # but prioritize same-DC bots first for lower initial latency.
260
  dc_clients = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in multi_clients]
261
- other_clients = [idx for idx in multi_clients if idx not in dc_clients]
262
-
263
- # Sort both groups by health/load
264
- dc_clients_sorted = sorted(dc_clients, key=_score)
265
- other_clients_sorted = sorted(other_clients, key=_score)
266
-
267
- # Combined pool prioritizing same-DC
268
- client_pool = dc_clients_sorted + other_clients_sorted
269
-
270
- if not client_pool:
271
- client_pool = [0] # fallback to primary bot
272
 
273
- # Primary client is the healthiest one from the preferred DC (if any)
274
  index = client_pool[0]
275
  tg_client = multi_clients[index]
276
 
 
91
  def select_best_client(target_dc: int) -> int:
92
  """Pick the best available client.
93
 
94
+ Score = work_loads + 3 × client_failures
95
+ Failures are weighted 3× so a bot that has been timing out / erroring
96
+ is deprioritised even if its current workload is low.
97
+ DC-aware selection is kept but currently commented out (uncomment to
98
+ prefer same-DC bots).
99
  """
100
  def _score(idx: int) -> int:
101
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
102
 
103
+ # --- DC-aware selection (Enabled) ---------------------------------------
104
  matching = [
105
  idx for idx, dc in client_dc_map.items()
106
  if dc == target_dc and idx in multi_clients
107
  ]
108
  if matching:
109
  selected = min(matching, key=_score)
110
+ LOGGER.debug("DC-match client %s (DC %s) score=%s", selected, target_dc, _score(selected))
111
  return selected
112
+ # ------------------------------------------------------------------------
113
 
 
114
  if multi_clients:
115
  selected = min(multi_clients.keys(), key=_score)
116
+ LOGGER.debug(
117
+ "Selected client %s (DC %s) score=%s",
118
+ selected, client_dc_map.get(selected, "?"), _score(selected),
119
+ )
120
  return selected
121
 
122
  return 0
 
263
  from Backend.pyrofork.bot import work_loads, client_failures
264
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
265
 
266
+ # Multi-connection striping: get all matching bots in DC, otherwise fallback globally
 
267
  dc_clients = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in multi_clients]
268
+ if dc_clients:
269
+ client_pool = sorted(dc_clients, key=_score)
270
+ else:
271
+ client_pool = [select_best_client(target_dc)]
 
 
 
 
 
 
 
272
 
273
+ # Primary client is the healthiest one
274
  index = client_pool[0]
275
  tg_client = multi_clients[index]
276
 
Backend/helper/custom_dl.py CHANGED
@@ -6,7 +6,7 @@ from typing import Dict, List, Union, Optional, Tuple, AsyncGenerator
6
  import traceback
7
  from fastapi import Request
8
  from pyrogram import Client, raw, utils
9
- from pyrogram.errors import AuthBytesInvalid, FileReferenceExpired
10
  from pyrogram.file_id import FileId, FileType, ThumbnailSource
11
  from pyrogram.session import Session, Auth
12
  from Backend.logger import LOGGER
@@ -23,17 +23,20 @@ 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
- < 10 MB/s → 1 MB (floor — never go below this; 512 KB is too slow)
27
- 10-30 MB/s → 2 MB
28
- > 30 MB/s → 4 MB (maximise throughput on fast sessions)
 
29
  """
30
  speed = client_avg_mbps.get(client_index, 0.0)
31
- if speed >= 30:
32
  return 4 * 1024 * 1024
33
- if speed >= 10:
34
  return 2 * 1024 * 1024
35
- # Unknown speed or < 10 MB/s → 1 MB floor (never start at 512 KB)
36
- return 1 * 1024 * 1024
 
 
37
 
38
  class ByteStreamer:
39
  CHUNK_SIZE = 1024 * 1024 # 1 MB
@@ -183,22 +186,19 @@ class ByteStreamer:
183
 
184
  LOGGER.debug("Striping stream %s across clients: %s", stream_id, active_pool)
185
 
186
- # Mutable reference so FileReferenceExpired handler can refresh it
187
- location_ref = [await self._get_location(file_id)]
188
 
189
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
190
  """Fetch one chunk with timeout, exponential back-off, and round-robin bot striping.
191
-
192
- Returns (seq_idx, bytes) on success or (seq_idx, None) on unrecoverable failure.
193
  """
194
  primary_client_idx = active_pool[seq_idx % len(active_pool)]
195
  primary_session = pool_sessions[primary_client_idx]
196
-
197
  tries = 0
198
  while tries < 3 and not stop_event.is_set():
199
  use_session = primary_session
200
  use_client_idx = primary_client_idx
201
-
202
  if tries >= 1 and len(active_pool) > 1:
203
  def _score(idx):
204
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
@@ -220,51 +220,21 @@ class ByteStreamer:
220
  r = await asyncio.wait_for(
221
  use_session.send(
222
  raw.functions.upload.GetFile(
223
- location=location_ref[0], offset=off, limit=chunk_size
224
  )
225
  ),
226
  timeout=15.0,
227
  )
228
  chunk_bytes = getattr(r, "bytes", None) if r else None
229
-
230
- # Empty bytes means Telegram returned nothing — treat as a
231
- # transient failure and retry (don't give up immediately).
232
- if chunk_bytes == b"" or chunk_bytes is None:
233
- tries += 1
234
- LOGGER.warning(
235
- "Chunk empty seq=%s off=%s try=%s client=%s — retrying",
236
- seq_idx, off, tries, use_client_idx,
237
- )
238
- # No sleep here — empty usually means EOF probe past file end;
239
- # sleeping would stall the event loop unnecessarily.
240
- continue
241
 
242
  # If we succeeded via a fallback, mark primary as degraded
243
  if use_client_idx != primary_client_idx:
244
  client_failures[primary_client_idx] = client_failures.get(primary_client_idx, 0) + 1
245
  return seq_idx, chunk_bytes
246
 
247
- except FileReferenceExpired:
248
- # File reference is stale — refresh and retry once
249
- LOGGER.warning(
250
- "FileReferenceExpired seq=%s off=%s client=%s — refreshing file location",
251
- seq_idx, off, use_client_idx,
252
- )
253
- try:
254
- # Clear cache so get_file_properties fetches a fresh message
255
- msg_id = getattr(file_id, "local_id", None)
256
- if msg_id and msg_id in self._file_id_cache:
257
- del self._file_id_cache[msg_id]
258
- chat_id_local = getattr(file_id, "chat_id", None)
259
- if msg_id and chat_id_local:
260
- fresh_fid = await self.get_file_properties(chat_id_local, msg_id)
261
- location_ref[0] = await self._get_location(fresh_fid)
262
- LOGGER.info("Refreshed file location after FileReferenceExpired")
263
- except Exception as ref_err:
264
- LOGGER.error("Could not refresh file reference: %s", ref_err)
265
- tries += 1
266
- await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
267
-
268
  except asyncio.TimeoutError:
269
  tries += 1
270
  client_failures[use_client_idx] = client_failures.get(use_client_idx, 0) + 1
@@ -272,15 +242,15 @@ class ByteStreamer:
272
  "Chunk timeout seq=%s off=%s try=%s client=%s",
273
  seq_idx, off, tries, use_client_idx,
274
  )
275
- await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
276
-
277
  except Exception as e:
278
  tries += 1
279
  LOGGER.debug(
280
  "Fetch chunk error seq=%s off=%s try=%s client=%s err=%s",
281
  seq_idx, off, tries, use_client_idx, getattr(e, "args", e),
282
  )
283
- await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
 
 
284
 
285
  LOGGER.error(
286
  "Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
@@ -298,11 +268,7 @@ class ByteStreamer:
298
  scheduled_tasks = {}
299
  results_buffer = {}
300
  next_to_put = 0
301
- # Drive as many concurrent fetches as we have active bots so all
302
- # clients are kept busy. Cap at a sane upper bound to avoid
303
- # overwhelming the queue.
304
- max_parallel = max(parallelism, len(active_pool), 1)
305
- max_parallel = min(max_parallel, 24) # hard cap
306
 
307
  initial = min(part_count, max_parallel)
308
  for i in range(initial):
@@ -340,14 +306,8 @@ class ByteStreamer:
340
  scheduled_tasks.pop(completed_seq, None)
341
 
342
  if chunk_bytes is None:
343
- LOGGER.error(
344
- "Unrecoverable chunk failure stream=%s seq=%s — terminating stream cleanly.",
345
- stream_id, seq_idx,
346
- )
347
- # Signal end-of-stream so the player retries from its
348
- # own buffer rather than playing corrupted silence.
349
- await q.put((None, None))
350
- return
351
 
352
  results_buffer[seq_idx] = chunk_bytes
353
 
 
6
  import traceback
7
  from fastapi import Request
8
  from pyrogram import Client, raw, utils
9
+ from pyrogram.errors import AuthBytesInvalid
10
  from pyrogram.file_id import FileId, FileType, ThumbnailSource
11
  from pyrogram.session import Session, Auth
12
  from Backend.logger import LOGGER
 
23
  """Return the best chunk size (bytes) for this client based on recent speed.
24
 
25
  Speed tiers:
26
+ < 5 MB/s → 512 KB (small chunks, faster first-byte on slow sessions)
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
+ if speed >= 5:
37
+ return 1 * 1024 * 1024
38
+ # Unknown speed or < 5 MB/s → start conservative
39
+ return 512 * 1024
40
 
41
  class ByteStreamer:
42
  CHUNK_SIZE = 1024 * 1024 # 1 MB
 
186
 
187
  LOGGER.debug("Striping stream %s across clients: %s", stream_id, active_pool)
188
 
189
+ location = await self._get_location(file_id)
 
190
 
191
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
192
  """Fetch one chunk with timeout, exponential back-off, and round-robin bot striping.
 
 
193
  """
194
  primary_client_idx = active_pool[seq_idx % len(active_pool)]
195
  primary_session = pool_sessions[primary_client_idx]
196
+
197
  tries = 0
198
  while tries < 3 and not stop_event.is_set():
199
  use_session = primary_session
200
  use_client_idx = primary_client_idx
201
+
202
  if tries >= 1 and len(active_pool) > 1:
203
  def _score(idx):
204
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
 
220
  r = await asyncio.wait_for(
221
  use_session.send(
222
  raw.functions.upload.GetFile(
223
+ location=location, offset=off, limit=chunk_size
224
  )
225
  ),
226
  timeout=15.0,
227
  )
228
  chunk_bytes = getattr(r, "bytes", None) if r else None
229
+
230
+ if chunk_bytes == b"":
231
+ return seq_idx, None
 
 
 
 
 
 
 
 
 
232
 
233
  # If we succeeded via a fallback, mark primary as degraded
234
  if use_client_idx != primary_client_idx:
235
  client_failures[primary_client_idx] = client_failures.get(primary_client_idx, 0) + 1
236
  return seq_idx, chunk_bytes
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  except asyncio.TimeoutError:
239
  tries += 1
240
  client_failures[use_client_idx] = client_failures.get(use_client_idx, 0) + 1
 
242
  "Chunk timeout seq=%s off=%s try=%s client=%s",
243
  seq_idx, off, tries, use_client_idx,
244
  )
 
 
245
  except Exception as e:
246
  tries += 1
247
  LOGGER.debug(
248
  "Fetch chunk error seq=%s off=%s try=%s client=%s err=%s",
249
  seq_idx, off, tries, use_client_idx, getattr(e, "args", e),
250
  )
251
+
252
+ # Exponential back-off: 0.5 s, 1 s, 2 s, 4 s, 8 s, 10 s (cap)
253
+ await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))
254
 
255
  LOGGER.error(
256
  "Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
 
268
  scheduled_tasks = {}
269
  results_buffer = {}
270
  next_to_put = 0
271
+ max_parallel = max(1, parallelism)
 
 
 
 
272
 
273
  initial = min(part_count, max_parallel)
274
  for i in range(initial):
 
306
  scheduled_tasks.pop(completed_seq, None)
307
 
308
  if chunk_bytes is None:
309
+ LOGGER.error("Chunk fetch returned empty for stream=%s seq=%s. Filling with zero bytes.", stream_id, seq_idx)
310
+ chunk_bytes = b"\x00" * chunk_size
 
 
 
 
 
 
311
 
312
  results_buffer[seq_idx] = chunk_bytes
313
 
Backend/pyrofork/clients.py CHANGED
@@ -27,11 +27,9 @@ async def start_client(client_id, token):
27
  api_id=Telegram.API_ID,
28
  api_hash=Telegram.API_HASH,
29
  bot_token=token,
30
- sleep_threshold=60,
31
  no_updates=True,
32
- in_memory=True,
33
- workers=8,
34
- max_concurrent_transmissions=20,
35
  ).start()
36
 
37
  try:
 
27
  api_id=Telegram.API_ID,
28
  api_hash=Telegram.API_HASH,
29
  bot_token=token,
30
+ sleep_threshold=100,
31
  no_updates=True,
32
+ in_memory=True
 
 
33
  ).start()
34
 
35
  try: