feat: add job progress, retry and rotating logs

This commit is contained in:
strsv committed 2026-11-06 07:52:16 +03:00
1 parent 626650e44a
commit c441d770e2
16 files changed
+297 -72

No files matched your search

+74 -3
View File
@@ -8,6 +8,7 @@ Binds to 127.0.0.1 by default: no auth, do not expose it to the internet.
import argparse
import json
import logging
import os
import queue
import re
@@ -23,6 +24,7 @@ import urllib.request
import webbrowser
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from logging.handlers import RotatingFileHandler
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE, "tools"))
@@ -47,6 +49,32 @@ 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
PROGRESS_RE = re.compile(r"^\s*(\d+)/(\d+)\b")
LOG = logging.getLogger("steambase")
LOG.setLevel(logging.INFO)
LOG.propagate = False
LOG.addHandler(logging.NullHandler())
def setup_logging(path=None):
"""Attach a rotating JSON-lines log under data/ (no request bodies)."""
path = path or os.path.join(BASE, "data", "server.log")
os.makedirs(os.path.dirname(path), exist_ok=True)
target = os.path.abspath(path)
for handler in LOG.handlers:
if isinstance(handler, RotatingFileHandler) and handler.baseFilename == target:
return handler
handler = RotatingFileHandler(target, maxBytes=1024 * 1024, backupCount=3, encoding="utf-8")
handler.setFormatter(logging.Formatter("%(message)s"))
LOG.addHandler(handler)
return handler
def log_event(event, **fields):
record = {"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), "event": event}
record.update(fields)
LOG.info(json.dumps(record, ensure_ascii=False))
CDN_COVER_NAMES = (
"library_600x900.jpg",
"library_capsule.jpg",
@@ -168,9 +196,10 @@ class JobManager:
def __init__(self):
self._lock = threading.Lock()
self._proc = None
self._last = None
self._state = {
"name": None, "running": False, "cancelled": False, "exit_code": None,
"started_at": None, "finished_at": None, "output": [],
"started_at": None, "finished_at": None, "progress": None, "output": [],
}
def start(self, name, args):
@@ -178,14 +207,23 @@ class JobManager:
if self._state["running"]:
return False
self._proc = None
self._last = (name, list(args))
self._state = {
"name": name, "running": True, "cancelled": False, "exit_code": None,
"started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"finished_at": None, "output": [],
"finished_at": None, "progress": None, "output": [],
}
log_event("job_start", name=name)
threading.Thread(target=self._run, args=(name, args), daemon=True).start()
return True
def retry(self):
with self._lock:
if self._state["running"] or not self._last:
return False
name, args = self._last
return self.start(name, args)
def cancel(self):
deadline = time.time() + 2
while True:
@@ -195,6 +233,7 @@ class JobManager:
proc = self._proc
if proc is not None:
self._state["cancelled"] = True
name = self._state["name"]
break
if time.time() >= deadline:
return False
@@ -207,11 +246,30 @@ class JobManager:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
log_event("job_cancel", name=name)
return True
def _update_progress(self, line, started):
match = PROGRESS_RE.match(line)
if not match:
return
current, total = int(match.group(1)), int(match.group(2))
if total <= 0 or current > total:
return
elapsed = time.monotonic() - started
eta = int(elapsed / current * (total - current)) if current else None
with self._lock:
self._state["progress"] = {
"current": current,
"total": total,
"percent": round(current / total * 100, 1),
"eta_seconds": max(0, eta) if eta is not None else None,
}
def _run(self, name, args):
code = None
proc = None
started = time.monotonic()
try:
proc = subprocess.Popen(
[sys.executable, "-u", *args], cwd=BASE,
@@ -220,9 +278,11 @@ class JobManager:
)
self._proc = proc
for line in proc.stdout:
line = line.rstrip()
with self._lock:
self._state["output"].append(line.rstrip())
self._state["output"].append(line)
self._state["output"] = self._state["output"][-80:]
self._update_progress(line, started)
code = proc.wait()
except Exception as exc:
with self._lock:
@@ -238,7 +298,10 @@ class JobManager:
self._state["running"] = False
self._state["exit_code"] = code
self._state["finished_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
cancelled = self._state["cancelled"]
self._proc = None
log_event("job_finish", name=name, exit_code=code, cancelled=cancelled,
duration_seconds=round(time.monotonic() - started, 1))
if name == "import":
try:
DETAILS.enqueue_many(missing_detail_ids(1000))
@@ -404,6 +467,7 @@ class Handler(BaseHTTPRequestHandler):
return
self._static(path)
except Exception as exc:
log_event("http_error", method="GET", path=path, error=str(exc))
self._error(500, str(exc))
def do_POST(self):
@@ -422,6 +486,8 @@ class Handler(BaseHTTPRequestHandler):
self._update_personal(appid, self._body())
elif path == "/api/job/cancel":
self._json({"cancelled": JOBS.cancel()})
elif path == "/api/job/retry":
self._json({"started": JOBS.retry()})
elif path == "/api/refresh":
body = self._body()
mode = body.get("mode", "incremental")
@@ -447,6 +513,7 @@ class Handler(BaseHTTPRequestHandler):
else:
self._error(404, "not found")
except Exception as exc:
log_event("http_error", method="POST", path=path, error=str(exc))
self._error(500, str(exc))
def _static(self, path):
@@ -887,6 +954,7 @@ def main():
args = ap.parse_args()
global DETAILS
setup_logging()
con = db.connect(db.DEFAULT_DB)
db.init(con)
db.seed_moods(con)
@@ -894,6 +962,7 @@ def main():
DETAILS = DetailsService(db.DEFAULT_DB, delay=1.4)
url = f"http://{args.host}:{args.port}/"
log_event("server_start", host=args.host, port=args.port)
print(f"SteamBase UI: {url}")
if args.open:
threading.Timer(0.7, lambda: webbrowser.open(url)).start()
@@ -902,6 +971,8 @@ def main():
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
log_event("server_stop")
if __name__ == "__main__":