Spaces:
Running

Nrighton233j commited on
Commit
1d875d5
·
1 Parent(s): 576867f

Lightning: least-busy load balancing, busy handling, search/info cache

Browse files
_old/lightning_integration.py.before-balancer ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ lightning_integration.py — Downloads service's connection to the extraction
3
+ workers (Lightning.ai + Railway yt-dlp servers). Tries each configured
4
+ server in order, falling back to the next one on timeout, connection
5
+ error, or a server-side failure. Servers that just failed are skipped
6
+ for a short while so requests don't keep waiting on a dead server.
7
+ """
8
+
9
+ import os
10
+ import threading
11
+ import time
12
+ import requests
13
+
14
+ # Ordered list of extractor base URLs. First is primary; later ones are
15
+ # used only if an earlier one fails, errors, or times out. Add/remove/
16
+ # reorder servers via the EXTRACTOR_URLS env var (comma-separated) without
17
+ # touching code.
18
+ EXTRACTOR_URLS = [
19
+ u.strip() for u in os.environ.get(
20
+ "EXTRACTOR_URLS",
21
+ "https://jextractor.brightonjosephkbj.blitz.cloud,"
22
+ "https://extractor3-git.obsidian.blitz.cloud"
23
+ ).split(",") if u.strip()
24
+ ]
25
+
26
+ SHARED_SECRET = os.environ["EXTRACT_SHARED_SECRET"]
27
+ PING_INTERVAL = 300
28
+ DOWN_FOR = 120 # seconds to skip a server after it fails
29
+
30
+ _down_until = {}
31
+ _lock = threading.Lock()
32
+ _keepalive_started = False
33
+
34
+
35
+ def _mark_down(base):
36
+ with _lock:
37
+ _down_until[base] = time.time() + DOWN_FOR
38
+
39
+
40
+ def _mark_up(base):
41
+ with _lock:
42
+ _down_until.pop(base, None)
43
+
44
+
45
+ def _ordered_servers():
46
+ """Healthy servers first (in configured order), recently failed ones
47
+ last, so we never end up with zero servers to try."""
48
+ now = time.time()
49
+ with _lock:
50
+ healthy = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) <= now]
51
+ down = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) > now]
52
+ return healthy + down
53
+
54
+
55
+ def _ping_loop(base):
56
+ while True:
57
+ try:
58
+ resp = requests.get(f"{base}/health", timeout=10)
59
+ if resp.status_code == 200:
60
+ _mark_up(base)
61
+ else:
62
+ _mark_down(base)
63
+ print(f"[keepalive] {base} status={resp.status_code}")
64
+ except Exception as e:
65
+ _mark_down(base)
66
+ print(f"[keepalive] {base} ping failed: {e}")
67
+ time.sleep(PING_INTERVAL)
68
+
69
+
70
+ def keep_lightning_awake():
71
+ global _keepalive_started
72
+ with _lock:
73
+ if _keepalive_started:
74
+ return
75
+ _keepalive_started = True
76
+ for base in EXTRACTOR_URLS:
77
+ threading.Thread(target=_ping_loop, args=(base,), daemon=True).start()
78
+
79
+
80
+ def _post_with_failover(path, json_body, timeout, label):
81
+ """POSTs json_body to path on each extractor, healthy ones first,
82
+ returning the first successful (200) JSON response. Moves to the next
83
+ server on timeout, connection error, 5xx, 408 or 429. Other 4xx errors
84
+ (bad request/URL) are raised immediately since another server won't
85
+ help. Raises the last error if every server fails."""
86
+ last_err = None
87
+ for base in _ordered_servers():
88
+ try:
89
+ resp = requests.post(
90
+ f"{base}{path}",
91
+ json=json_body,
92
+ headers={"X-Auth-Token": SHARED_SECRET},
93
+ timeout=(5, timeout),
94
+ )
95
+ except requests.exceptions.RequestException as e:
96
+ _mark_down(base)
97
+ last_err = RuntimeError(f"{label} failed on {base}: {e}")
98
+ print(f"[{label}] {base} errored ({e}), trying next")
99
+ continue
100
+
101
+ if resp.status_code == 200:
102
+ _mark_up(base)
103
+ return resp.json()
104
+
105
+ err = RuntimeError(
106
+ f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
107
+ )
108
+ if resp.status_code in (502, 503, 504):
109
+ _mark_down(base)
110
+ if resp.status_code < 500 and resp.status_code not in (408, 429):
111
+ raise err
112
+ last_err = err
113
+ print(f"[{label}] {base} returned {resp.status_code}, trying next")
114
+ raise last_err or RuntimeError(f"{label}: no extractor servers configured")
115
+
116
+
117
+ def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
118
+ """Returns dict: {job_id, stream_url, title, mimetype, ext}.
119
+ Does not download anything itself — just resolves the URL.
120
+ Enhancement (video upscale/audio boost) adds real time - up to ~900s
121
+ worst case for video - so timeout auto-scales unless explicitly
122
+ overridden. Tries each configured extractor in order."""
123
+ if timeout is None:
124
+ timeout = 950 if (enhance and mode == "video") else 300
125
+ return _post_with_failover(
126
+ "/extract",
127
+ {"url": url, "mode": mode, "quality": quality, "enhance": enhance},
128
+ timeout,
129
+ "extract",
130
+ )
131
+
132
+
133
+ def get_info(url, timeout=25):
134
+ """Metadata-only lookup via an extractor's /info route (yt-dlp
135
+ --skip-download). Returns {title, uploader, duration, thumbnail,
136
+ webpage_url, extractor}. Tries each configured extractor in order."""
137
+ return _post_with_failover("/info", {"url": url}, timeout, "info")
138
+
139
+
140
+ _fetch_slots = threading.BoundedSemaphore(int(os.environ.get("MAX_CONCURRENT_FETCHES", "3")))
141
+ MAX_FETCH_BYTES = int(os.environ.get("MAX_FETCH_BYTES", str(100 * 1024 * 1024)))
142
+ MAX_FETCH_SECONDS = int(os.environ.get("MAX_FETCH_SECONDS", "600"))
143
+
144
+
145
+ def fetch_bytes(stream_url, timeout=300):
146
+ """Downloads the resolved stream_url into memory and returns the raw
147
+ bytes. At most MAX_CONCURRENT_FETCHES run at once; files over
148
+ MAX_FETCH_BYTES or slower than MAX_FETCH_SECONDS are rejected. Not part
149
+ of the failover chain - stream_url already points at one server."""
150
+ with _fetch_slots:
151
+ started = time.time()
152
+ with requests.get(stream_url, timeout=timeout, stream=True) as resp:
153
+ if resp.status_code != 200:
154
+ raise RuntimeError(f"download from stream_url failed ({resp.status_code})")
155
+ declared = int(resp.headers.get("Content-Length") or 0)
156
+ if declared > MAX_FETCH_BYTES:
157
+ raise RuntimeError("file too large")
158
+ buf = bytearray()
159
+ for chunk in resp.iter_content(chunk_size=65536):
160
+ if chunk:
161
+ buf.extend(chunk)
162
+ if len(buf) > MAX_FETCH_BYTES:
163
+ raise RuntimeError("file too large")
164
+ if time.time() - started > MAX_FETCH_SECONDS:
165
+ raise RuntimeError("download took too long")
166
+ return bytes(buf)
167
+
168
+
169
+ def search_tracks(query, limit=10, timeout=30):
170
+ """Metadata-only search by keyword (e.g. YouTube) via an extractor.
171
+ Returns a list of {title, url, thumbnail, duration, uploader} dicts -
172
+ no extraction/download happens here, just candidate results for the
173
+ app to show a picker before committing to a /remote/fetch. Tries each
174
+ configured extractor in order."""
175
+ result = _post_with_failover(
176
+ "/search", {"query": query, "limit": limit}, timeout, "search"
177
+ )
178
+ return result.get("results", [])
lightning_integration.py CHANGED
@@ -42,14 +42,28 @@ def _mark_up(base):
42
  _down_until.pop(base, None)
43
 
44
 
 
 
 
 
 
 
 
45
  def _ordered_servers():
46
- """Healthy servers first (in configured order), recently failed ones
47
- last, so we never end up with zero servers to try."""
 
48
  now = time.time()
 
49
  with _lock:
 
50
  healthy = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) <= now]
51
  down = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) > now]
52
- return healthy + down
 
 
 
 
53
 
54
 
55
  def _ping_loop(base):
@@ -78,40 +92,61 @@ def keep_lightning_awake():
78
 
79
 
80
  def _post_with_failover(path, json_body, timeout, label):
81
- """POSTs json_body to path on each extractor, healthy ones first,
82
- returning the first successful (200) JSON response. Moves to the next
83
- server on timeout, connection error, 5xx, 408 or 429. Other 4xx errors
84
- (bad request/URL) are raised immediately since another server won't
85
- help. Raises the last error if every server fails."""
 
 
 
86
  last_err = None
87
- for base in _ordered_servers():
88
- try:
89
- resp = requests.post(
90
- f"{base}{path}",
91
- json=json_body,
92
- headers={"X-Auth-Token": SHARED_SECRET},
93
- timeout=(5, timeout),
94
- )
95
- except requests.exceptions.RequestException as e:
96
- _mark_down(base)
97
- last_err = RuntimeError(f"{label} failed on {base}: {e}")
98
- print(f"[{label}] {base} errored ({e}), trying next")
99
- continue
 
 
 
 
 
 
 
 
100
 
101
- if resp.status_code == 200:
102
- _mark_up(base)
103
- return resp.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- err = RuntimeError(
106
- f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
107
- )
108
- if resp.status_code in (502, 503, 504):
109
- _mark_down(base)
110
- if resp.status_code < 500 and resp.status_code not in (408, 429):
111
- raise err
112
- last_err = err
113
- print(f"[{label}] {base} returned {resp.status_code}, trying next")
114
- raise last_err or RuntimeError(f"{label}: no extractor servers configured")
115
 
116
 
117
  def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
@@ -130,11 +165,35 @@ def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=N
130
  )
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def get_info(url, timeout=25):
134
  """Metadata-only lookup via an extractor's /info route (yt-dlp
135
  --skip-download). Returns {title, uploader, duration, thumbnail,
136
  webpage_url, extractor}. Tries each configured extractor in order."""
137
- return _post_with_failover("/info", {"url": url}, timeout, "info")
138
 
139
 
140
  _fetch_slots = threading.BoundedSemaphore(int(os.environ.get("MAX_CONCURRENT_FETCHES", "3")))
@@ -172,7 +231,10 @@ def search_tracks(query, limit=10, timeout=30):
172
  no extraction/download happens here, just candidate results for the
173
  app to show a picker before committing to a /remote/fetch. Tries each
174
  configured extractor in order."""
175
- result = _post_with_failover(
176
- "/search", {"query": query, "limit": limit}, timeout, "search"
 
 
 
177
  )
178
  return result.get("results", [])
 
42
  _down_until.pop(base, None)
43
 
44
 
45
+ _inflight = {}
46
+ _busy_until = {}
47
+ _rr = 0
48
+ BUSY_COOLDOWN = 5 # seconds to prefer other servers after a 429
49
+ BUSY_WAIT = int(os.environ.get("EXTRACTOR_BUSY_WAIT", "20"))
50
+
51
+
52
  def _ordered_servers():
53
+ """Least-busy healthy servers first (ties rotate so equal servers share
54
+ load), servers that just said busy next, recently failed ones last."""
55
+ global _rr
56
  now = time.time()
57
+ n = max(len(EXTRACTOR_URLS), 1)
58
  with _lock:
59
+ _rr += 1
60
  healthy = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) <= now]
61
  down = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) > now]
62
+ free = [b for b in healthy if _busy_until.get(b, 0) <= now]
63
+ busy = [b for b in healthy if _busy_until.get(b, 0) > now]
64
+ free.sort(key=lambda b: (_inflight.get(b, 0),
65
+ (EXTRACTOR_URLS.index(b) - _rr) % n))
66
+ return free + busy + down
67
 
68
 
69
  def _ping_loop(base):
 
92
 
93
 
94
  def _post_with_failover(path, json_body, timeout, label):
95
+ """POSTs to the least-busy healthy extractor. A server answering 429
96
+ (busy) is skipped at once and the others are tried; if every server is
97
+ busy, waits up to EXTRACTOR_BUSY_WAIT seconds for a free slot.
98
+ Timeouts, connection errors and 5xx move on to the next server; other
99
+ 4xx errors (bad URL) are raised immediately."""
100
+ if not EXTRACTOR_URLS:
101
+ raise RuntimeError(f"{label}: no extractor servers configured")
102
+ deadline = time.time() + BUSY_WAIT
103
  last_err = None
104
+ while True:
105
+ all_busy = True
106
+ for base in _ordered_servers():
107
+ with _lock:
108
+ _inflight[base] = _inflight.get(base, 0) + 1
109
+ try:
110
+ resp = requests.post(
111
+ f"{base}{path}",
112
+ json=json_body,
113
+ headers={"X-Auth-Token": SHARED_SECRET},
114
+ timeout=(5, timeout),
115
+ )
116
+ except requests.exceptions.RequestException as e:
117
+ _mark_down(base)
118
+ all_busy = False
119
+ last_err = RuntimeError(f"{label} failed on {base}: {e}")
120
+ print(f"[{label}] {base} errored ({e}), trying next")
121
+ continue
122
+ finally:
123
+ with _lock:
124
+ _inflight[base] -= 1
125
 
126
+ if resp.status_code == 200:
127
+ _mark_up(base)
128
+ return resp.json()
129
+ if resp.status_code == 429:
130
+ with _lock:
131
+ _busy_until[base] = time.time() + BUSY_COOLDOWN
132
+ last_err = RuntimeError(f"{label}: {base} busy")
133
+ continue
134
+
135
+ all_busy = False
136
+ err = RuntimeError(
137
+ f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
138
+ )
139
+ if resp.status_code in (502, 503, 504):
140
+ _mark_down(base)
141
+ if resp.status_code < 500 and resp.status_code != 408:
142
+ raise err
143
+ last_err = err
144
+ print(f"[{label}] {base} returned {resp.status_code}, trying next")
145
 
146
+ if all_busy and time.time() < deadline:
147
+ time.sleep(1)
148
+ continue
149
+ raise last_err or RuntimeError(f"{label}: all extractors failed")
 
 
 
 
 
 
150
 
151
 
152
  def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
 
165
  )
166
 
167
 
168
+ _cache = {}
169
+ _cache_lock = threading.Lock()
170
+ CACHE_TTL = int(os.environ.get("EXTRACTOR_CACHE_SECONDS", "300"))
171
+
172
+
173
+ def _cached(key, fn):
174
+ if CACHE_TTL <= 0:
175
+ return fn()
176
+ now = time.time()
177
+ with _cache_lock:
178
+ hit = _cache.get(key)
179
+ if hit and hit[0] > now:
180
+ return hit[1]
181
+ val = fn()
182
+ with _cache_lock:
183
+ if len(_cache) > 500:
184
+ for k in [k for k, v in _cache.items() if v[0] <= now]:
185
+ _cache.pop(k, None)
186
+ if len(_cache) > 500:
187
+ _cache.clear()
188
+ _cache[key] = (now + CACHE_TTL, val)
189
+ return val
190
+
191
+
192
  def get_info(url, timeout=25):
193
  """Metadata-only lookup via an extractor's /info route (yt-dlp
194
  --skip-download). Returns {title, uploader, duration, thumbnail,
195
  webpage_url, extractor}. Tries each configured extractor in order."""
196
+ return _cached(("info", url), lambda: _post_with_failover("/info", {"url": url}, timeout, "info"))
197
 
198
 
199
  _fetch_slots = threading.BoundedSemaphore(int(os.environ.get("MAX_CONCURRENT_FETCHES", "3")))
 
231
  no extraction/download happens here, just candidate results for the
232
  app to show a picker before committing to a /remote/fetch. Tries each
233
  configured extractor in order."""
234
+ result = _cached(
235
+ ("search", query.strip().lower(), limit),
236
+ lambda: _post_with_failover(
237
+ "/search", {"query": query, "limit": limit}, timeout, "search"
238
+ ),
239
  )
240
  return result.get("results", [])