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

Revert "Multi-Connection Striping (#44)" (#47)

Browse files

This reverts commit 844cc3a81ecf5208c5d1d02127ddc1a35840c8cc.

Backend/fastapi/routes/stream_routes.py CHANGED
@@ -259,19 +259,7 @@ async def media_streamer(
259
  target_dc = file_id.dc_id
260
  LOGGER.debug(f"File msg_id={msg_id} is in DC {target_dc}")
261
 
262
- def _score(idx: int) -> int:
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
 
277
  if tg_client not in _streamer_by_client:
@@ -328,7 +316,6 @@ async def media_streamer(
328
  meta=meta,
329
  parallelism=parallelism,
330
  request=request,
331
- client_pool=client_pool,
332
  )
333
 
334
  asyncio.create_task(track_usage_from_stats(stream_id, token, token_data))
 
259
  target_dc = file_id.dc_id
260
  LOGGER.debug(f"File msg_id={msg_id} is in DC {target_dc}")
261
 
262
+ index = select_best_client(target_dc)
 
 
 
 
 
 
 
 
 
 
 
 
263
  tg_client = multi_clients[index]
264
 
265
  if tg_client not in _streamer_by_client:
 
316
  meta=meta,
317
  parallelism=parallelism,
318
  request=request,
 
319
  )
320
 
321
  asyncio.create_task(track_usage_from_stats(stream_id, token, token_data))
Backend/helper/custom_dl.py CHANGED
@@ -2,7 +2,7 @@ import asyncio
2
  import time
3
  import secrets
4
  from collections import deque
5
- from typing import Dict, List, Union, Optional, Tuple, AsyncGenerator
6
  import traceback
7
  from fastapi import Request
8
  from pyrogram import Client, raw, utils
@@ -117,20 +117,19 @@ class ByteStreamer:
117
 
118
  async def prefetch_stream(
119
  self,
120
- file_id,
121
  client_index: int,
122
  offset: int,
123
  first_part_cut: int,
124
  last_part_cut: int,
125
  part_count: int,
126
  chunk_size: int,
127
- prefetch: int,
128
- stream_id: str,
129
- meta: dict,
130
- parallelism: int = 1,
131
- request = None,
132
- client_pool: list = None,
133
- ) -> AsyncGenerator[bytes, None]:
134
  if not stream_id:
135
  stream_id = secrets.token_hex(8)
136
 
@@ -161,59 +160,47 @@ class ByteStreamer:
161
  q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
162
  stop_event = asyncio.Event()
163
 
164
- multi_clients = getattr(self, "_multi_clients", None)
165
- if multi_clients is None:
166
- from Backend.pyrofork.bot import multi_clients
167
-
168
- client_pool = client_pool or [client_index]
169
-
170
- active_pool = []
171
- pool_sessions = {}
172
- for c in client_pool:
173
- c_streamer = ByteStreamer._instances.get(c)
174
- if c_streamer is None and c in multi_clients:
175
- c_streamer = ByteStreamer(multi_clients[c], c)
176
- if c_streamer:
177
- try:
178
- pool_sessions[c] = await c_streamer._get_media_session(file_id)
179
- active_pool.append(c)
180
- except Exception as e:
181
- LOGGER.error("Could not get session for bot %s: %s", c, e)
182
-
183
- if not active_pool:
184
- active_pool = [client_index]
185
- pool_sessions[client_index] = await self._get_media_session(file_id)
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)
205
  fallback_idx = min(
206
- (i for i in active_pool if i != primary_client_idx),
207
  key=_score,
208
  default=None,
209
  )
210
  if fallback_idx is not None:
211
- use_session = pool_sessions[fallback_idx]
212
- use_client_idx = fallback_idx
213
- LOGGER.debug(
214
- "Chunk fallback: seq=%s try=%s primary=%s → fallback=%s",
215
- seq_idx, tries, primary_client_idx, fallback_idx,
216
- )
 
 
 
 
 
 
 
217
 
218
  # --- attempt the fetch with a hard timeout ---
219
  try:
@@ -231,8 +218,8 @@ class ByteStreamer:
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:
@@ -254,7 +241,7 @@ class ByteStreamer:
254
 
255
  LOGGER.error(
256
  "Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
257
- seq_idx, off, primary_client_idx,
258
  )
259
  return seq_idx, None
260
 
 
2
  import time
3
  import secrets
4
  from collections import deque
5
+ from typing import Dict, List, Union, Optional, Tuple
6
  import traceback
7
  from fastapi import Request
8
  from pyrogram import Client, raw, utils
 
117
 
118
  async def prefetch_stream(
119
  self,
120
+ file_id: FileId,
121
  client_index: int,
122
  offset: int,
123
  first_part_cut: int,
124
  last_part_cut: int,
125
  part_count: int,
126
  chunk_size: int,
127
+ prefetch: int = 3,
128
+ stream_id: Optional[str] = None,
129
+ meta: Optional[dict] = None,
130
+ parallelism: int = 2,
131
+ request: Optional[Request] = None,
132
+ ):
 
133
  if not stream_id:
134
  stream_id = secrets.token_hex(8)
135
 
 
160
  q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
161
  stop_event = asyncio.Event()
162
 
163
+ media_session = await self._get_media_session(file_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  location = await self._get_location(file_id)
165
 
166
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
167
+ """Fetch one chunk with timeout, exponential back-off, and bot fallback.
168
+
169
+ Retry schedule (max 3 tries):
170
+ tries 0 → same bot / same session, 15 s timeout each
171
+ tries 1-2 → try a healthier fallback bot (if available),
172
+ still with 15 s timeout
173
+ On every TimeoutError the primary client's failure counter is incremented
174
+ so select_best_client will avoid it for future requests.
175
  """
 
 
 
176
  tries = 0
177
  while tries < 3 and not stop_event.is_set():
178
+ # --- choose which media session to use this attempt ---
179
+ use_session = media_session
180
+ use_client_idx = client_index
181
+ if tries >= 1 and len(multi_clients) > 1:
182
+ # Pick the best *other* client by score = workload + 3×failures
183
  def _score(idx):
184
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
185
  fallback_idx = min(
186
+ (i for i in multi_clients if i != client_index),
187
  key=_score,
188
  default=None,
189
  )
190
  if fallback_idx is not None:
191
+ fb_streamer = ByteStreamer._instances.get(fallback_idx)
192
+ if fb_streamer is None:
193
+ fb_streamer = ByteStreamer(multi_clients[fallback_idx], fallback_idx)
194
+ try:
195
+ use_session = await fb_streamer._get_media_session(file_id)
196
+ use_client_idx = fallback_idx
197
+ LOGGER.debug(
198
+ "Chunk fallback: seq=%s try=%s primary=%s → fallback=%s",
199
+ seq_idx, tries, client_index, fallback_idx,
200
+ )
201
+ except Exception:
202
+ use_session = media_session # revert if fallback session fails
203
+ use_client_idx = client_index
204
 
205
  # --- attempt the fetch with a hard timeout ---
206
  try:
 
218
  return seq_idx, None
219
 
220
  # If we succeeded via a fallback, mark primary as degraded
221
+ if use_client_idx != client_index:
222
+ client_failures[client_index] = client_failures.get(client_index, 0) + 1
223
  return seq_idx, chunk_bytes
224
 
225
  except asyncio.TimeoutError:
 
241
 
242
  LOGGER.error(
243
  "Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
244
+ seq_idx, off, client_index,
245
  )
246
  return seq_idx, None
247