Spaces:
Running
Running
Nrighton233j commited on
Commit ·
5c19e7b
1
Parent(s): 9345159
Lightning: skip failed servers, smarter failover, per-server keepalive
Browse files- _old/lightning_integration.py.before-speed +116 -0
- lightning_integration.py +79 -31
_old/lightning_integration.py.before-speed
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 non-200 response.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
import requests
|
| 12 |
+
|
| 13 |
+
# Ordered list of extractor base URLs. First is primary; later ones are
|
| 14 |
+
# used only if an earlier one fails, errors, or times out. Add/remove/
|
| 15 |
+
# reorder servers via the EXTRACTOR_URLS env var (comma-separated) without
|
| 16 |
+
# touching code.
|
| 17 |
+
EXTRACTOR_URLS = [
|
| 18 |
+
u.strip() for u in os.environ.get(
|
| 19 |
+
"EXTRACTOR_URLS",
|
| 20 |
+
"https://jextractor.brightonjosephkbj.blitz.cloud,"
|
| 21 |
+
"https://8000-01kz0f2nmwxxsga2pnywxqw0nk.cloudspaces.litng.ai,"
|
| 22 |
+
"https://extractor-production-e55e.up.railway.app"
|
| 23 |
+
).split(",") if u.strip()
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
SHARED_SECRET = os.environ["EXTRACT_SHARED_SECRET"]
|
| 27 |
+
PING_INTERVAL = 300
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def keep_lightning_awake():
|
| 31 |
+
def _loop():
|
| 32 |
+
while True:
|
| 33 |
+
for base in EXTRACTOR_URLS:
|
| 34 |
+
try:
|
| 35 |
+
resp = requests.get(f"{base}/health", timeout=10)
|
| 36 |
+
print(f"[keepalive] {base} status={resp.status_code}")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"[keepalive] {base} ping failed: {e}")
|
| 39 |
+
time.sleep(PING_INTERVAL)
|
| 40 |
+
|
| 41 |
+
threading.Thread(target=_loop, daemon=True).start()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _post_with_failover(path, json_body, timeout, label):
|
| 45 |
+
"""POSTs json_body to path on each extractor in EXTRACTOR_URLS, in
|
| 46 |
+
order, returning the first successful (200) JSON response. Moves to
|
| 47 |
+
the next server on timeout, connection error, or non-200. Raises the
|
| 48 |
+
last error if every server fails."""
|
| 49 |
+
last_err = None
|
| 50 |
+
for base in EXTRACTOR_URLS:
|
| 51 |
+
try:
|
| 52 |
+
resp = requests.post(
|
| 53 |
+
f"{base}{path}",
|
| 54 |
+
json=json_body,
|
| 55 |
+
headers={"X-Auth-Token": SHARED_SECRET},
|
| 56 |
+
timeout=(5, timeout),
|
| 57 |
+
)
|
| 58 |
+
if resp.status_code == 200:
|
| 59 |
+
return resp.json()
|
| 60 |
+
last_err = RuntimeError(
|
| 61 |
+
f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
|
| 62 |
+
)
|
| 63 |
+
print(f"[{label}] {base} returned {resp.status_code}, trying next")
|
| 64 |
+
except requests.exceptions.RequestException as e:
|
| 65 |
+
last_err = RuntimeError(f"{label} failed on {base}: {e}")
|
| 66 |
+
print(f"[{label}] {base} errored ({e}), trying next")
|
| 67 |
+
raise last_err
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
|
| 71 |
+
"""Returns dict: {job_id, stream_url, title, mimetype, ext}.
|
| 72 |
+
Does not download anything itself — just resolves the URL.
|
| 73 |
+
Enhancement (video upscale/audio boost) adds real time - up to ~900s
|
| 74 |
+
worst case for video - so timeout auto-scales unless explicitly
|
| 75 |
+
overridden. Tries each configured extractor in order."""
|
| 76 |
+
if timeout is None:
|
| 77 |
+
timeout = 950 if (enhance and mode == "video") else 300
|
| 78 |
+
return _post_with_failover(
|
| 79 |
+
"/extract",
|
| 80 |
+
{"url": url, "mode": mode, "quality": quality, "enhance": enhance},
|
| 81 |
+
timeout,
|
| 82 |
+
"extract",
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_info(url, timeout=25):
|
| 87 |
+
"""Metadata-only lookup via an extractor's /info route (yt-dlp
|
| 88 |
+
--skip-download). Returns {title, uploader, duration, thumbnail,
|
| 89 |
+
webpage_url, extractor}. Tries each configured extractor in order."""
|
| 90 |
+
return _post_with_failover("/info", {"url": url}, timeout, "info")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def fetch_bytes(stream_url, timeout=300):
|
| 94 |
+
"""Downloads the resolved stream_url fully into memory, returns the
|
| 95 |
+
raw bytes. Not part of the failover chain - stream_url already points
|
| 96 |
+
at whichever specific server resolved it."""
|
| 97 |
+
resp = requests.get(stream_url, timeout=timeout, stream=True)
|
| 98 |
+
if resp.status_code != 200:
|
| 99 |
+
raise RuntimeError(f"download from stream_url failed ({resp.status_code})")
|
| 100 |
+
chunks = []
|
| 101 |
+
for chunk in resp.iter_content(chunk_size=65536):
|
| 102 |
+
if chunk:
|
| 103 |
+
chunks.append(chunk)
|
| 104 |
+
return b"".join(chunks)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def search_tracks(query, limit=10, timeout=30):
|
| 108 |
+
"""Metadata-only search by keyword (e.g. YouTube) via an extractor.
|
| 109 |
+
Returns a list of {title, url, thumbnail, duration, uploader} dicts -
|
| 110 |
+
no extraction/download happens here, just candidate results for the
|
| 111 |
+
app to show a picker before committing to a /remote/fetch. Tries each
|
| 112 |
+
configured extractor in order."""
|
| 113 |
+
result = _post_with_failover(
|
| 114 |
+
"/search", {"query": query, "limit": limit}, timeout, "search"
|
| 115 |
+
)
|
| 116 |
+
return result.get("results", [])
|
lightning_integration.py
CHANGED
|
@@ -2,7 +2,8 @@
|
|
| 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
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
|
@@ -25,29 +26,66 @@ EXTRACTOR_URLS = [
|
|
| 25 |
|
| 26 |
SHARED_SECRET = os.environ["EXTRACT_SHARED_SECRET"]
|
| 27 |
PING_INTERVAL = 300
|
|
|
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
def keep_lightning_awake():
|
| 31 |
-
def _loop():
|
| 32 |
-
while True:
|
| 33 |
-
for base in EXTRACTOR_URLS:
|
| 34 |
-
try:
|
| 35 |
-
resp = requests.get(f"{base}/health", timeout=10)
|
| 36 |
-
print(f"[keepalive] {base} status={resp.status_code}")
|
| 37 |
-
except Exception as e:
|
| 38 |
-
print(f"[keepalive] {base} ping failed: {e}")
|
| 39 |
-
time.sleep(PING_INTERVAL)
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
def _post_with_failover(path, json_body, timeout, label):
|
| 45 |
-
"""POSTs json_body to path on each extractor
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 49 |
last_err = None
|
| 50 |
-
for base in
|
| 51 |
try:
|
| 52 |
resp = requests.post(
|
| 53 |
f"{base}{path}",
|
|
@@ -55,16 +93,26 @@ def _post_with_failover(path, json_body, timeout, label):
|
|
| 55 |
headers={"X-Auth-Token": SHARED_SECRET},
|
| 56 |
timeout=(5, timeout),
|
| 57 |
)
|
| 58 |
-
if resp.status_code == 200:
|
| 59 |
-
return resp.json()
|
| 60 |
-
last_err = RuntimeError(
|
| 61 |
-
f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
|
| 62 |
-
)
|
| 63 |
-
print(f"[{label}] {base} returned {resp.status_code}, trying next")
|
| 64 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 65 |
last_err = RuntimeError(f"{label} failed on {base}: {e}")
|
| 66 |
print(f"[{label}] {base} errored ({e}), trying next")
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
|
|
@@ -94,13 +142,13 @@ def fetch_bytes(stream_url, timeout=300):
|
|
| 94 |
"""Downloads the resolved stream_url fully into memory, returns the
|
| 95 |
raw bytes. Not part of the failover chain - stream_url already points
|
| 96 |
at whichever specific server resolved it."""
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
return b"".join(chunks)
|
| 105 |
|
| 106 |
|
|
|
|
| 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
|
|
|
|
| 26 |
|
| 27 |
SHARED_SECRET = os.environ["EXTRACT_SHARED_SECRET"]
|
| 28 |
PING_INTERVAL = 300
|
| 29 |
+
DOWN_FOR = 120 # seconds to skip a server after it fails
|
| 30 |
|
| 31 |
+
_down_until = {}
|
| 32 |
+
_lock = threading.Lock()
|
| 33 |
+
_keepalive_started = False
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
def _mark_down(base):
|
| 37 |
+
with _lock:
|
| 38 |
+
_down_until[base] = time.time() + DOWN_FOR
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _mark_up(base):
|
| 42 |
+
with _lock:
|
| 43 |
+
_down_until.pop(base, None)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _ordered_servers():
|
| 47 |
+
"""Healthy servers first (in configured order), recently failed ones
|
| 48 |
+
last, so we never end up with zero servers to try."""
|
| 49 |
+
now = time.time()
|
| 50 |
+
with _lock:
|
| 51 |
+
healthy = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) <= now]
|
| 52 |
+
down = [b for b in EXTRACTOR_URLS if _down_until.get(b, 0) > now]
|
| 53 |
+
return healthy + down
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _ping_loop(base):
|
| 57 |
+
while True:
|
| 58 |
+
try:
|
| 59 |
+
resp = requests.get(f"{base}/health", timeout=10)
|
| 60 |
+
if resp.status_code == 200:
|
| 61 |
+
_mark_up(base)
|
| 62 |
+
else:
|
| 63 |
+
_mark_down(base)
|
| 64 |
+
print(f"[keepalive] {base} status={resp.status_code}")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
_mark_down(base)
|
| 67 |
+
print(f"[keepalive] {base} ping failed: {e}")
|
| 68 |
+
time.sleep(PING_INTERVAL)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def keep_lightning_awake():
|
| 72 |
+
global _keepalive_started
|
| 73 |
+
with _lock:
|
| 74 |
+
if _keepalive_started:
|
| 75 |
+
return
|
| 76 |
+
_keepalive_started = True
|
| 77 |
+
for base in EXTRACTOR_URLS:
|
| 78 |
+
threading.Thread(target=_ping_loop, args=(base,), daemon=True).start()
|
| 79 |
|
| 80 |
|
| 81 |
def _post_with_failover(path, json_body, timeout, label):
|
| 82 |
+
"""POSTs json_body to path on each extractor, healthy ones first,
|
| 83 |
+
returning the first successful (200) JSON response. Moves to the next
|
| 84 |
+
server on timeout, connection error, 5xx, 408 or 429. Other 4xx errors
|
| 85 |
+
(bad request/URL) are raised immediately since another server won't
|
| 86 |
+
help. Raises the last error if every server fails."""
|
| 87 |
last_err = None
|
| 88 |
+
for base in _ordered_servers():
|
| 89 |
try:
|
| 90 |
resp = requests.post(
|
| 91 |
f"{base}{path}",
|
|
|
|
| 93 |
headers={"X-Auth-Token": SHARED_SECRET},
|
| 94 |
timeout=(5, timeout),
|
| 95 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
except requests.exceptions.RequestException as e:
|
| 97 |
+
_mark_down(base)
|
| 98 |
last_err = RuntimeError(f"{label} failed on {base}: {e}")
|
| 99 |
print(f"[{label}] {base} errored ({e}), trying next")
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
if resp.status_code == 200:
|
| 103 |
+
_mark_up(base)
|
| 104 |
+
return resp.json()
|
| 105 |
+
|
| 106 |
+
err = RuntimeError(
|
| 107 |
+
f"{label} failed on {base} ({resp.status_code}): {resp.text[:500]}"
|
| 108 |
+
)
|
| 109 |
+
if resp.status_code in (502, 503, 504):
|
| 110 |
+
_mark_down(base)
|
| 111 |
+
if resp.status_code < 500 and resp.status_code not in (408, 429):
|
| 112 |
+
raise err
|
| 113 |
+
last_err = err
|
| 114 |
+
print(f"[{label}] {base} returned {resp.status_code}, trying next")
|
| 115 |
+
raise last_err or RuntimeError(f"{label}: no extractor servers configured")
|
| 116 |
|
| 117 |
|
| 118 |
def extract_stream(url, mode="audio", quality="medium", enhance=False, timeout=None):
|
|
|
|
| 142 |
"""Downloads the resolved stream_url fully into memory, returns the
|
| 143 |
raw bytes. Not part of the failover chain - stream_url already points
|
| 144 |
at whichever specific server resolved it."""
|
| 145 |
+
with requests.get(stream_url, timeout=timeout, stream=True) as resp:
|
| 146 |
+
if resp.status_code != 200:
|
| 147 |
+
raise RuntimeError(f"download from stream_url failed ({resp.status_code})")
|
| 148 |
+
chunks = []
|
| 149 |
+
for chunk in resp.iter_content(chunk_size=65536):
|
| 150 |
+
if chunk:
|
| 151 |
+
chunks.append(chunk)
|
| 152 |
return b"".join(chunks)
|
| 153 |
|
| 154 |
|