File size: 27,918 Bytes
1404692
f87315f
 
d3a7f5b
36dde81
d3a7f5b
36dde81
 
 
d3a7f5b
36dde81
14af9d0
36dde81
 
 
f697c3b
36dde81
 
 
 
 
1404692
d3a7f5b
854dc06
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
36dde81
 
 
 
 
 
 
 
1404692
36dde81
 
f87315f
d3a7f5b
f697c3b
d3a7f5b
f697c3b
36dde81
d3a7f5b
f697c3b
 
d3a7f5b
 
36dde81
d3a7f5b
 
f87315f
854dc06
 
d3a7f5b
36dde81
854dc06
d3a7f5b
36dde81
d3a7f5b
 
 
 
 
36dde81
 
d3a7f5b
854dc06
 
 
d3a7f5b
 
 
 
 
854dc06
d3a7f5b
36dde81
854dc06
 
 
 
d3a7f5b
1404692
36dde81
1404692
36dde81
 
1404692
 
36dde81
 
 
 
d3a7f5b
36dde81
d3a7f5b
 
f2554c1
d3a7f5b
 
 
 
 
 
2c766ea
cbaaf8b
f2554c1
 
 
f87315f
 
 
f2554c1
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
 
 
 
f2554c1
f87315f
 
 
 
 
 
36dde81
 
f87315f
 
36dde81
f87315f
 
 
36dde81
f87315f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
f87315f
 
 
36dde81
d3a7f5b
f697c3b
f87315f
f697c3b
f87315f
f697c3b
 
f87315f
d3a7f5b
 
f87315f
14af9d0
 
7787e06
d3a7f5b
f697c3b
 
 
f87315f
 
 
d3a7f5b
f87315f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
 
 
 
 
 
14af9d0
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fea4f05
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
 
 
f87315f
d3a7f5b
 
1404692
f87315f
 
 
 
36dde81
 
f87315f
 
 
 
d3a7f5b
f87315f
 
 
36dde81
 
f87315f
d3a7f5b
 
 
 
 
 
1404692
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
d3a7f5b
36dde81
d3a7f5b
 
 
 
36dde81
 
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
 
 
 
 
 
 
36dde81
 
d3a7f5b
36dde81
 
d3a7f5b
 
 
36dde81
 
d3a7f5b
36dde81
 
d3a7f5b
36dde81
1404692
d3a7f5b
1404692
d3a7f5b
36dde81
d3a7f5b
 
36dde81
d3a7f5b
 
 
36dde81
 
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
 
f697c3b
d3a7f5b
 
 
 
36dde81
 
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
36dde81
d3a7f5b
36dde81
d3a7f5b
 
f697c3b
 
 
 
f87315f
36dde81
 
f697c3b
 
 
 
 
 
 
 
36dde81
f697c3b
d3a7f5b
36dde81
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
 
d3a7f5b
 
1404692
 
d3a7f5b
1404692
d3a7f5b
1404692
d3a7f5b
 
1404692
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
 
 
f697c3b
 
36dde81
2c766ea
f697c3b
 
36dde81
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c766ea
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c766ea
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import asyncio
import random
import re
import secrets
import time
import traceback
from collections import deque
from typing import Dict, List, Optional, Tuple, Union

from fastapi import Request
from pyrogram import Client, raw
from pyrogram.errors import AuthBytesInvalid
from pyrogram.file_id import FileId
from pyrogram.session import Auth, Session

from Backend import db
from Backend.helper.exceptions import FileNotFound
from Backend.helper.pyro import get_file_ids
from Backend.logger import LOGGER
from Backend.helper.bounded import BoundedDict
from Backend.pyrofork.bot import client_avg_mbps, client_dc_map, client_failures, multi_clients, work_loads

ACTIVE_STREAMS: Dict[str, Dict] = {}
RECENT_STREAMS = deque(maxlen=20)
STALE_STREAM_IDLE = 180
_STALE_CLEANER_STARTED = False


async def _cleanup_stale_streams():
    while True:
        try:
            await asyncio.sleep(30)
            now = time.time()
            stale = []
            for sid, entry in list(ACTIVE_STREAMS.items()):
                last = entry.get("last_ts") or entry.get("start_ts") or 0
                status = entry.get("status") or "active"
                total = entry.get("total_bytes") or 0
                idle = now - last
                if status != "active" or idle > STALE_STREAM_IDLE or (total == 0 and idle > 60):
                    stale.append(sid)
            for sid in stale:
                try:
                    entry = ACTIVE_STREAMS.pop(sid, None)
                    if entry:
                        entry["status"] = "stale"
                        entry["end_ts"] = now
                        RECENT_STREAMS.appendleft(entry)
                        idx = entry.get("client_index")
                        if entry.pop("load_held", False) and idx in work_loads:
                            work_loads[idx] = max(0, work_loads[idx] - 1)
                except Exception:
                    pass
        except Exception:
            pass


def _ensure_stale_cleaner():
    global _STALE_CLEANER_STARTED
    if not _STALE_CLEANER_STARTED:
        _STALE_CLEANER_STARTED = True
        asyncio.create_task(_cleanup_stale_streams())


#----- Telegram file byte streamer with prefetch, multi-client parallelism, and telemetry
class ByteStreamer:
    CHUNK_SIZE = 1024 * 1024
    CLEAN_INTERVAL = 30 * 60
    _instances: Dict[int, "ByteStreamer"] = {}

    def __init__(self, client: Client, client_index: int = -1):
        self.client = client
        self.client_index = client_index
        self._file_id_cache = BoundedDict(2000)
        self._session_lock = asyncio.Lock()
        if client_index >= 0:
            ByteStreamer._instances[client_index] = self
        asyncio.create_task(self._clean_cache())
        asyncio.create_task(self._prewarm_sessions())
        _ensure_stale_cleaner()

    async def _prewarm_sessions(self):
        common_dcs = [1, 2, 4, 5]
        test_mode = await self.client.storage.test_mode()
        current_dc = await self.client.storage.dc_id()
        for dc in common_dcs:
            if dc in self.client.media_sessions:
                continue
            try:
                auth_key = await self.client.storage.auth_key() if dc == current_dc else await Auth(self.client, dc, test_mode).create()
                session = Session(self.client, dc, auth_key, test_mode, is_media=True)
                session.no_updates = True
                session.timeout = 30
                session.sleep_threshold = 60
                await session.start()
                imported = dc == current_dc
                for _ in range(0 if imported else 6):
                    try:
                        exported = await self.client.invoke(raw.functions.auth.ExportAuthorization(dc_id=dc))
                        await session.send(raw.functions.auth.ImportAuthorization(id=exported.id,bytes=exported.bytes,))
                        imported = True
                        break
                    except AuthBytesInvalid:
                        await asyncio.sleep(0.5)
                    except OSError:
                        await asyncio.sleep(1)
                    except Exception:
                        break
                if imported and dc not in self.client.media_sessions:
                    self.client.media_sessions[dc] = session
                else:
                    await session.stop()
            except Exception:
                continue

    #----- Fetch (and cache) Telegram FileId properties for a message
    async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
        cache_key = (int(chat_id), int(message_id))
        if cache_key not in self._file_id_cache:
            file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
            if not file_id:
                LOGGER.warning("Message %s not found in chat %s", message_id, chat_id)
                raise FileNotFound
            self._file_id_cache[cache_key] = file_id
        return self._file_id_cache[cache_key]

    #----- Build a prefetching, range-aware streaming generator for a file
    async def prefetch_stream(
        self,
        file_id: FileId,
        client_index: int,
        offset: int,
        first_part_cut: int,
        last_part_cut: int,
        part_count: int,
        chunk_size: int,
        prefetch: int,
        parallelism: int,
        stream_id: Optional[str] = None,
        meta: Optional[dict] = None,
        request: Optional[Request] = None,
        chat_id: Optional[int] = None,
        message_id: Optional[int] = None,
        extra_clients: Optional[List] = None,
    ):
        if not stream_id:
            stream_id = secrets.token_hex(8)

        now = time.time()
        registry_entry = {
            "stream_id": stream_id,
            "msg_id": getattr(file_id, "local_id", None) or None,
            "chat_id": getattr(file_id, "chat_id", None),
            "dc_id": file_id.dc_id,
            "client_index": client_index,
            "start_ts": now,
            "last_ts": now,
            "total_bytes": 0,
            "avg_mbps": 0.0,
            "instant_mbps": 0.0,
            "peak_mbps": 0.0,
            "recent_measurements": deque(maxlen=3),
            "status": "active",
            "part_count": part_count,
            "prefetch": prefetch,
            "meta": meta or {},
            "load_held": True,
        }

        ACTIVE_STREAMS[stream_id] = registry_entry
        stream_entry = registry_entry
        work_loads[client_index] += 1

        queue_maxsize = max(1, prefetch)
        q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
        stop_event = asyncio.Event()

        media_session = await self._get_media_session(file_id)
        location_box: List[object] = [await self._get_location(file_id)]
        async def _make_refresh_fn(loc_b, streamer_ref, file_id_ref):
            async def _refresh() -> bool:
                if not chat_id or not message_id:
                    return False
                try:
                    cache_key = (int(chat_id), int(message_id))
                    streamer_ref._file_id_cache.pop(cache_key, None)
                    fresh = await get_file_ids(streamer_ref.client, chat_id, message_id)
                    if fresh:
                        streamer_ref._file_id_cache[cache_key] = fresh
                        loc_b[0] = await ByteStreamer._get_location(fresh)
                        return True
                except Exception as exc:
                    LOGGER.warning("Location refresh failed for chat=%s msg_id=%s: %s", chat_id, message_id, exc)
                return False
            return _refresh

        primary_refresh = await _make_refresh_fn(location_box, self, file_id)
        session_pool = [(client_index, media_session, location_box, primary_refresh)]

        if extra_clients:
            for ec_idx, ec_streamer, ec_file_id in extra_clients:
                try:
                    ec_session = await ec_streamer._get_media_session(ec_file_id)
                    ec_loc_box = [await ByteStreamer._get_location(ec_file_id)]
                    ec_refresh = await _make_refresh_fn(ec_loc_box, ec_streamer, ec_file_id)
                    session_pool.append((ec_idx, ec_session, ec_loc_box, ec_refresh))
                except Exception as e:
                    LOGGER.warning("Skipping extra client %s (session setup failed): %s", ec_idx, e)

        async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
            tries = 0
            flood_tries = 0
            while tries < 3 and flood_tries < 5 and not stop_event.is_set():
                c_idx, c_session, c_loc_box, c_refresh = session_pool[(seq_idx + tries) % len(session_pool)]
                try:
                    r = await asyncio.wait_for(
                        c_session.send(
                            raw.functions.upload.GetFile(
                                location=c_loc_box[0], offset=off, limit=chunk_size
                            )
                        ),
                        timeout=15.0,
                    )
                    chunk_bytes = getattr(r, "bytes", None) if r else None

                    if chunk_bytes == b"":
                        return seq_idx, None

                    return seq_idx, chunk_bytes

                except asyncio.TimeoutError:
                    tries += 1
                    client_failures[c_idx] = client_failures.get(c_idx, 0) + 1
                    await asyncio.sleep(min(0.5 * (2 ** (tries - 1)), 10.0))

                except Exception as e:
                    err_str = str(e)

                    if "FILE_REFERENCE" in err_str or "file_reference" in err_str.lower():
                        await c_refresh()

                    flood_m = re.search(r'wait of (\d+) second', err_str, re.IGNORECASE)
                    if flood_m:
                        required = float(flood_m.group(1))
                        jitter = random.uniform(0.5, 2.0)
                        wait = required + jitter
                        flood_tries += 1
                        await asyncio.sleep(wait)
                    else:
                        tries += 1
                        backoff = min(0.5 * (2 ** (tries - 1)), 10.0)
                        await asyncio.sleep(backoff)
            return seq_idx, None

        async def producer():
            scheduled_tasks = {}
            try:
                if part_count <= 0:
                    await q.put((None, None))
                    return

                next_to_schedule = 0
                results_buffer = {}
                next_to_put = 0
                max_parallel = max(1, parallelism)

                initial = min(part_count, max_parallel)
                for i in range(initial):
                    seq = next_to_schedule
                    off = offset + seq * chunk_size
                    task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
                    scheduled_tasks[seq] = task
                    next_to_schedule += 1

                while next_to_put < part_count:
                    if stop_event.is_set():
                        break

                    if not scheduled_tasks:
                        seq = next_to_schedule
                        off = offset + seq * chunk_size
                        task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
                        scheduled_tasks[seq] = task
                        next_to_schedule += 1

                    done, _ = await asyncio.wait(scheduled_tasks.values(), return_when=asyncio.FIRST_COMPLETED)

                    for completed in done:
                        try:
                            completed_seq = None
                            for k, t in list(scheduled_tasks.items()):
                                if t is completed:
                                    completed_seq = k
                                    break

                            if completed_seq is None:
                                continue

                            seq_idx, chunk_bytes = completed.result()
                            scheduled_tasks.pop(completed_seq, None)

                            if chunk_bytes is None:
                                await q.put((None, None))
                                return

                            results_buffer[seq_idx] = chunk_bytes

                            if next_to_schedule < part_count:
                                seq = next_to_schedule
                                off = offset + seq * chunk_size
                                task = asyncio.create_task(fetch_chunk_with_retries(seq, off))
                                scheduled_tasks[seq] = task
                                next_to_schedule += 1

                        except asyncio.CancelledError:
                            raise
                        except Exception as e:
                            LOGGER.exception("Error processing completed fetch task: %s%s", e, traceback.format_exc())
                            await q.put((None, None))
                            return

                    while next_to_put in results_buffer:
                        chunk_bytes = results_buffer.pop(next_to_put)
                        await q.put((offset + next_to_put * chunk_size, chunk_bytes))
                        next_to_put += 1

                await q.put((None, None))

            except asyncio.CancelledError:
                try:
                    await q.put((None, None))
                except Exception:
                    pass
                raise
            except Exception as e:
                LOGGER.exception("Producer unexpected error for stream %s: %s", stream_id, e)
                try:
                    await q.put((None, None))
                except Exception:
                    pass
            finally:
                stop_event.set()
                if scheduled_tasks:
                    for t in scheduled_tasks.values():
                        if not t.done():
                            t.cancel()
                    try:
                        await asyncio.gather(*scheduled_tasks.values(), return_exceptions=True)
                    except Exception:
                        pass
                    scheduled_tasks.clear()

        async def consumer_generator():
            producer_task = asyncio.create_task(producer())
            current_part_idx = 1
            _disconnect_check_counter = 0

            try:
                while True:
                    _disconnect_check_counter += 1
                    if _disconnect_check_counter % 8 == 0:
                        try:
                            if request and await request.is_disconnected():
                                stop_event.set()
                                stream_entry["status"] = "cancelled"
                                break
                        except Exception:
                            pass

                    try:
                        off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
                    except asyncio.TimeoutError:
                        LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
                        stop_event.set()
                        stream_entry["status"] = "error"
                        break

                    if off_chunk is None:
                        break

                    off, chunk = off_chunk
                    if off is None and chunk is None:
                        break

                    if part_count == 1:
                        out_chunk = chunk[first_part_cut:last_part_cut]
                    elif current_part_idx == 1:
                        out_chunk = chunk[first_part_cut:]
                    elif current_part_idx == part_count:
                        out_chunk = chunk[:last_part_cut]
                    else:
                        out_chunk = chunk

                    try:
                        chunk_len = len(out_chunk)
                    except Exception:
                        chunk_len = 0

                    now_ts = time.time()
                    last_ts = stream_entry.get("last_ts") or stream_entry.get("start_ts") or now_ts
                    elapsed = now_ts - last_ts
                    if elapsed <= 0:
                        elapsed = 1e-6

                    recent = stream_entry.setdefault("recent_measurements", deque(maxlen=3))
                    recent.append((chunk_len, elapsed))

                    if len(recent) >= 2:
                        total_bytes = sum(b for b, _ in recent)
                        total_time = sum(t for _, t in recent)
                        instant_mbps = min((total_bytes / (1024 * 1024)) / max(total_time, 0.01), 1000.0)
                    else:
                        instant_mbps = 0.0

                    stream_entry["total_bytes"] = stream_entry.get("total_bytes", 0) + chunk_len
                    stream_entry["last_ts"] = now_ts

                    start_ts = stream_entry.get("start_ts") or now_ts
                    total_time = now_ts - start_ts
                    if total_time <= 0:
                        total_time = 1e-6

                    stream_entry["avg_mbps"] = (stream_entry["total_bytes"] / (1024 * 1024)) / total_time
                    stream_entry["instant_mbps"] = instant_mbps

                    if instant_mbps > stream_entry.get("peak_mbps", 0.0):
                        stream_entry["peak_mbps"] = instant_mbps

                    yield out_chunk

                    current_part_idx += 1

            except asyncio.CancelledError:
                stop_event.set()
                if not producer_task.done():
                    producer_task.cancel()
                stream_entry["status"] = "cancelled"
                raise
            except Exception as e:
                LOGGER.exception("Consumer error for stream %s: %s", stream_id, e)
                stop_event.set()
                stream_entry["status"] = "error"
                if not producer_task.done():
                    producer_task.cancel()
            finally:
                stop_event.set()
                if not producer_task.done():
                    try:
                        producer_task.cancel()
                        await asyncio.wait_for(producer_task, timeout=2.0)
                    except (Exception, asyncio.CancelledError):
                        pass

                try:
                    end_ts = time.time()
                    total_bytes = stream_entry.get("total_bytes", 0)
                    start_ts = stream_entry.get("start_ts") or end_ts
                    duration = end_ts - start_ts if end_ts > start_ts else 0.0
                    avg_mbps = (total_bytes / (1024 * 1024)) / (duration if duration > 0 else 1e-6)

                    stream_entry.update({
                        "end_ts": end_ts,
                        "duration": duration,
                        "avg_mbps": avg_mbps,
                        "status": "finished" if stream_entry.get("status") == "active" else stream_entry.get("status", "finished"),
                        "parallelism": parallelism,
                        "chunk_size": chunk_size,
                    })

                    prev = client_avg_mbps.get(client_index, 0.0)
                    if prev == 0.0:
                        client_avg_mbps[client_index] = avg_mbps
                    else:
                        client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps

                    asyncio.create_task(db.log_stream_stats(stream_entry))

                    async def delayed_pop():
                        await asyncio.sleep(3)
                        try:
                            if stream_id in ACTIVE_STREAMS:
                                RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(stream_id))
                        except Exception:
                            pass

                    asyncio.create_task(delayed_pop())
                finally:
                    if stream_entry.pop("load_held", False):
                        work_loads[client_index] = max(0, work_loads.get(client_index, 0) - 1)

                stop_event.set()

        return consumer_generator()

    async def _get_media_session(self, file_id: FileId) -> Session:
        dc = file_id.dc_id
        media_session = self.client.media_sessions.get(dc)

        if media_session:
            return media_session

        async with self._session_lock:
            media_session = self.client.media_sessions.get(dc)
            if media_session:
                return media_session

            test_mode = await self.client.storage.test_mode()
            current_dc = await self.client.storage.dc_id()

            if dc != current_dc:
                auth_key = await Auth(self.client, dc, test_mode).create()
            else:
                auth_key = await self.client.storage.auth_key()

            session = Session(self.client, dc, auth_key, test_mode, is_media=True)
            session.no_updates = True
            session.timeout = 30 
            session.sleep_threshold = 60 

            await session.start()

            if dc != current_dc:
                for _ in range(6):
                    try:
                        exported = await self.client.invoke(raw.functions.auth.ExportAuthorization(dc_id=dc))
                        await session.send(raw.functions.auth.ImportAuthorization(id=exported.id, bytes=exported.bytes))
                        break
                    except AuthBytesInvalid:
                        await asyncio.sleep(0.5)
                    except OSError:
                        await asyncio.sleep(1)

            self.client.media_sessions[dc] = session
            return session

    @staticmethod
    async def _get_location(file_id: FileId) -> Union[
        raw.types.InputDocumentFileLocation,
    ]:
        return raw.types.InputDocumentFileLocation(
            id=file_id.media_id,
            access_hash=file_id.access_hash,
            file_reference=file_id.file_reference,
            thumb_size=file_id.thumbnail_size,
        )

    async def _clean_cache(self) -> None:
        while True:
            await asyncio.sleep(self.CLEAN_INTERVAL)
            self._file_id_cache.clear()
            LOGGER.debug("ByteStreamer: cleared file_id cache")


#----- Speed test helper (runs independently, on-demand per file)
TEST_CHUNK_SIZE = 100 * 1024 * 1024


#----- Download a fixed slice from one client and measure throughput
async def _speed_test_single_client(
    client: Client,
    client_index: int,
    chat_id: int,
    message_id: int,
    progress_callback=None,
) -> dict:
    dc_id = client_dc_map.get(client_index, "?")
    result = {
        "client_index": client_index,
        "dc_id": dc_id,
        "ping_ms": None,
        "speed_mbps": None,
        "time_taken_sec": None,
        "bytes_downloaded": 0,
        "error": None,
    }
    try:
        streamer = ByteStreamer(client)
        file_id = await streamer.get_file_properties(chat_id, message_id)

        media_session = await streamer._get_media_session(file_id)
        location = await ByteStreamer._get_location(file_id)
        ping_start = time.perf_counter()
        tiny = await media_session.send(
            raw.functions.upload.GetFile(location=location, offset=0, limit=4096)
        )
        ping_end = time.perf_counter()
        ping_ms = (ping_end - ping_start) * 1000
        result["ping_ms"] = round(ping_ms, 2)

        if not getattr(tiny, "bytes", None):
            result["error"] = "No data on ping probe"
            return result
        dl_start = time.perf_counter()
        last_progress_time = dl_start
        total_bytes = 0
        chunk_size = 512 * 1024  
        max_concurrent_chunks = 8
        queue = asyncio.Queue()
        target_offsets = list(range(0, TEST_CHUNK_SIZE, chunk_size))
        for off in target_offsets:
            queue.put_nowait(off)
        eof_reached = False
        
        async def fetch_chunk_worker():
            nonlocal total_bytes, last_progress_time, eof_reached
            while not queue.empty() and not eof_reached:
                offset = queue.get_nowait()
                fetch_size = min(chunk_size, TEST_CHUNK_SIZE - offset)
                try:
                    r = await asyncio.wait_for(
                        media_session.send(
                            raw.functions.upload.GetFile(
                                location=location, offset=offset, limit=fetch_size
                            )
                        ),
                        timeout=15.0,
                    )
                    chunk = getattr(r, "bytes", None)
                    if not chunk:
                        eof_reached = True
                        continue
                    bytes_got = len(chunk)
                    total_bytes += bytes_got
                    if bytes_got < fetch_size:
                        eof_reached = True
                    now = time.perf_counter()
                    if progress_callback and (now - last_progress_time) >= 1.0:
                        elapsed_so_far = now - dl_start
                        if elapsed_so_far > 0:
                            current_speed = (total_bytes / (1024 * 1024)) / elapsed_so_far
                            prog_res = dict(result)
                            prog_res["bytes_downloaded"] = total_bytes
                            prog_res["time_taken_sec"] = round(elapsed_so_far, 3)
                            prog_res["speed_mbps"] = round(current_speed, 3)
                            if asyncio.iscoroutinefunction(progress_callback):
                                asyncio.create_task(progress_callback(prog_res))
                            else:
                                progress_callback(prog_res)
                        last_progress_time = now

                except asyncio.TimeoutError:
                    LOGGER.debug(
                        "Speed-test chunk timeout client=%s offset=%s (skipping)",
                        client_index, offset,
                    )
                except Exception as e:
                    LOGGER.debug(
                        "Speed-test fetch error client=%s offset=%s: %s",
                        client_index, offset, e,
                    )
                    
                finally:
                    queue.task_done()
        workers = [
            asyncio.create_task(fetch_chunk_worker())
            for _ in range(max_concurrent_chunks)
        ]
        
        await queue.join()
        for w in workers:
            w.cancel()

        dl_end = time.perf_counter()
        elapsed = dl_end - dl_start
        if elapsed <= 0:
            elapsed = 1e-6

        speed_mbps = (total_bytes / (1024 * 1024)) / elapsed
        result["bytes_downloaded"] = total_bytes
        result["time_taken_sec"] = round(elapsed, 3)
        result["speed_mbps"] = round(speed_mbps, 3)

    except Exception as exc:
        result["error"] = str(exc)
        LOGGER.warning("Speed test failed for client %s (DC %s): %s", client_index, dc_id, exc)

    return result


#----- Run the speed test across every connected client, fastest first
async def run_speed_test(chat_id: int, message_id: int) -> List[dict]:
    if not multi_clients:
        return [{"error": "No bot clients connected"}]

    tasks = [
        _speed_test_single_client(client, idx, chat_id, message_id)
        for idx, client in multi_clients.items()
    ]

    results = await asyncio.gather(*tasks, return_exceptions=False)
    results.sort(
        key=lambda r: r.get("speed_mbps") or -1,
        reverse=True,
    )
    return list(results)