feat: add tests, CI and P0 reliability features
This commit is contained in:
1 parent
0754065dae
commit
626650e44a
22 files changed
+1576
-49
No files matched your search
+106
-3
@@ -14,6 +14,7 @@ import re
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -44,6 +45,7 @@ except SystemExit:
|
||||
LIB_CACHE = os.path.join(STEAM_ROOT, "appcache", "librarycache") if STEAM_ROOT else None
|
||||
CACHE_DIR = os.path.join(BASE, "cache", "covers")
|
||||
IMAGE_LOCK = threading.Lock()
|
||||
COVER_MISSING_TTL = 7 * 24 * 60 * 60
|
||||
CACHE_COVER_NAMES = steam_source.COVER_ORDER
|
||||
CDN_COVER_NAMES = (
|
||||
"library_600x900.jpg",
|
||||
@@ -165,8 +167,9 @@ class JobManager:
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
self._proc = None
|
||||
self._state = {
|
||||
"name": None, "running": False, "exit_code": None,
|
||||
"name": None, "running": False, "cancelled": False, "exit_code": None,
|
||||
"started_at": None, "finished_at": None, "output": [],
|
||||
}
|
||||
|
||||
@@ -174,22 +177,48 @@ class JobManager:
|
||||
with self._lock:
|
||||
if self._state["running"]:
|
||||
return False
|
||||
self._proc = None
|
||||
self._state = {
|
||||
"name": name, "running": True, "exit_code": None,
|
||||
"name": name, "running": True, "cancelled": False, "exit_code": None,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"finished_at": None, "output": [],
|
||||
}
|
||||
threading.Thread(target=self._run, args=(name, args), daemon=True).start()
|
||||
return True
|
||||
|
||||
def cancel(self):
|
||||
deadline = time.time() + 2
|
||||
while True:
|
||||
with self._lock:
|
||||
if not self._state["running"]:
|
||||
return False
|
||||
proc = self._proc
|
||||
if proc is not None:
|
||||
self._state["cancelled"] = True
|
||||
break
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(0.02)
|
||||
try:
|
||||
proc.terminate()
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
return True
|
||||
|
||||
def _run(self, name, args):
|
||||
code = None
|
||||
proc = None
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", *args], cwd=BASE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace",
|
||||
)
|
||||
self._proc = proc
|
||||
for line in proc.stdout:
|
||||
with self._lock:
|
||||
self._state["output"].append(line.rstrip())
|
||||
@@ -200,10 +229,16 @@ class JobManager:
|
||||
self._state["output"].append(str(exc))
|
||||
code = -1
|
||||
finally:
|
||||
if proc is not None and proc.stdout is not None:
|
||||
try:
|
||||
proc.stdout.close()
|
||||
except OSError:
|
||||
pass
|
||||
with self._lock:
|
||||
self._state["running"] = False
|
||||
self._state["exit_code"] = code
|
||||
self._state["finished_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
self._proc = None
|
||||
if name == "import":
|
||||
try:
|
||||
DETAILS.enqueue_many(missing_detail_ids(1000))
|
||||
@@ -335,7 +370,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
super().log_message(fmt, *args)
|
||||
|
||||
def _send(self, status, body, content_type="application/json; charset=utf-8",
|
||||
cache=False, max_age=86400):
|
||||
cache=False, max_age=86400, extra_headers=None):
|
||||
if isinstance(body, str):
|
||||
body = body.encode("utf-8")
|
||||
self.send_response(status)
|
||||
@@ -343,6 +378,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control",
|
||||
f"public, max-age={max_age}" if cache else "no-store")
|
||||
for name, value in (extra_headers or {}).items():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
@@ -383,6 +420,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif path.startswith("/api/personal/"):
|
||||
appid = int(path.rsplit("/", 1)[1])
|
||||
self._update_personal(appid, self._body())
|
||||
elif path == "/api/job/cancel":
|
||||
self._json({"cancelled": JOBS.cancel()})
|
||||
elif path == "/api/refresh":
|
||||
body = self._body()
|
||||
mode = body.get("mode", "incremental")
|
||||
@@ -451,6 +490,31 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return None
|
||||
return None
|
||||
|
||||
def _cover_marker(self, appid):
|
||||
return os.path.join(CACHE_DIR, str(appid), ".missing")
|
||||
|
||||
def _cover_missing_fresh(self, appid):
|
||||
path = self._cover_marker(appid)
|
||||
try:
|
||||
return time.time() - os.path.getmtime(path) < COVER_MISSING_TTL
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def _mark_cover_missing(self, appid):
|
||||
path = self._cover_marker(appid)
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(str(int(time.time())))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _clear_cover_missing(self, appid):
|
||||
try:
|
||||
os.remove(self._cover_marker(appid))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _cover(self, appid):
|
||||
app_cache = os.path.join(CACHE_DIR, str(appid))
|
||||
|
||||
@@ -458,15 +522,22 @@ class Handler(BaseHTTPRequestHandler):
|
||||
for name in CACHE_COVER_NAMES:
|
||||
path = os.path.join(app_cache, name)
|
||||
if os.path.isfile(path):
|
||||
self._clear_cover_missing(appid)
|
||||
self._serve_image(path)
|
||||
return
|
||||
|
||||
# 2. art already downloaded by the Steam client (old and new layout)
|
||||
local = steam_source.find_cover(appid, LIB_CACHE)
|
||||
if local:
|
||||
self._clear_cover_missing(appid)
|
||||
self._serve_image(local)
|
||||
return
|
||||
|
||||
# Do not hammer Steam CDN for apps known to have no cover.
|
||||
if self._cover_missing_fresh(appid):
|
||||
self._error(404, "no cover")
|
||||
return
|
||||
|
||||
# 3. header_image from the cached store details (new hashed CDN URL)
|
||||
con = connect()
|
||||
try:
|
||||
@@ -478,6 +549,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if row:
|
||||
data = self._download_cover(row["header_image"], os.path.join(app_cache, "header.jpg"))
|
||||
if data:
|
||||
self._clear_cover_missing(appid)
|
||||
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
||||
return
|
||||
|
||||
@@ -487,9 +559,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{name}"
|
||||
data = self._download_cover(url, path)
|
||||
if data:
|
||||
self._clear_cover_missing(appid)
|
||||
self._send(200, data, "image/jpeg", cache=True, max_age=2592000)
|
||||
return
|
||||
|
||||
self._mark_cover_missing(appid)
|
||||
self._error(404, "no cover")
|
||||
|
||||
def _api_get(self, path, qs):
|
||||
@@ -509,6 +583,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
con.close()
|
||||
elif path == "/api/job":
|
||||
self._json(JOBS.status())
|
||||
elif path == "/api/backup":
|
||||
self._backup()
|
||||
elif path.startswith("/api/cover/"):
|
||||
self._cover(int(path.rsplit("/", 1)[1]))
|
||||
elif path.startswith("/api/game/"):
|
||||
@@ -517,6 +593,33 @@ class Handler(BaseHTTPRequestHandler):
|
||||
else:
|
||||
self._error(404, "not found")
|
||||
|
||||
def _backup(self):
|
||||
fd, tmp_path = tempfile.mkstemp(prefix="steambase-backup-", suffix=".db")
|
||||
os.close(fd)
|
||||
try:
|
||||
source = db.connect(db.DEFAULT_DB)
|
||||
try:
|
||||
target = sqlite3.connect(tmp_path)
|
||||
try:
|
||||
source.backup(target)
|
||||
finally:
|
||||
target.close()
|
||||
finally:
|
||||
source.close()
|
||||
with open(tmp_path, "rb") as fh:
|
||||
data = fh.read()
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
||||
self._send(
|
||||
200, data, "application/octet-stream", cache=False,
|
||||
extra_headers={
|
||||
"Content-Disposition": f'attachment; filename="steambase-{stamp}.db"',
|
||||
})
|
||||
finally:
|
||||
try:
|
||||
os.remove(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _meta(self):
|
||||
con = connect()
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user