feat: add job progress, retry and rotating logs
This commit is contained in:
1 parent
626650e44a
commit
c441d770e2
16 files changed
+297
-72
No files matched your search
+74
-3
@@ -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__":
|
||||
|
||||
+36
-1
@@ -705,6 +705,14 @@ document.addEventListener("wheel", (e) => {
|
||||
|
||||
let jobTimer = null;
|
||||
|
||||
function formatEta(seconds) {
|
||||
if (seconds == null) return "";
|
||||
if (seconds < 60) return `${Math.max(1, Math.round(seconds))} с`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const rest = Math.round(seconds % 60);
|
||||
return `${minutes} мин${rest ? ` ${rest} с` : ""}`;
|
||||
}
|
||||
|
||||
async function pollJob() {
|
||||
try {
|
||||
const st = await api("/api/job");
|
||||
@@ -718,11 +726,22 @@ async function pollJob() {
|
||||
cancel.hidden = !busy;
|
||||
cancel.disabled = false;
|
||||
}
|
||||
const retry = $("#jobRetry");
|
||||
if (retry) {
|
||||
retry.hidden = busy || !st.name;
|
||||
retry.disabled = false;
|
||||
}
|
||||
const el = $("#jobStatus");
|
||||
if (busy) {
|
||||
const label = st.name === "translate" ? "перевод" : "обновление БД";
|
||||
const last = (st.output || []).slice(-1)[0] || "";
|
||||
el.textContent = `${label}… ${last}`.trim();
|
||||
const p = st.progress;
|
||||
let extra = "";
|
||||
if (p && p.total) {
|
||||
extra = ` ${p.current}/${p.total} (${p.percent}%)`;
|
||||
if (p.eta_seconds != null) extra += ` · ~${formatEta(p.eta_seconds)}`;
|
||||
}
|
||||
el.textContent = `${label}…${extra} ${last}`.trim();
|
||||
await loadMeta();
|
||||
clearTimeout(jobTimer);
|
||||
jobTimer = setTimeout(pollJob, 1500);
|
||||
@@ -775,6 +794,22 @@ $("#jobCancel").addEventListener("click", async (e) => {
|
||||
e.currentTarget.disabled = false;
|
||||
}
|
||||
});
|
||||
$("#jobRetry").addEventListener("click", async (e) => {
|
||||
e.currentTarget.disabled = true;
|
||||
try {
|
||||
const r = await api("/api/job/retry", { method: "POST", body: "{}" });
|
||||
if (r.started) {
|
||||
$("#jobStatus").textContent = "запуск…";
|
||||
pollJob();
|
||||
} else {
|
||||
toast("Нет задачи для повтора");
|
||||
e.currentTarget.disabled = false;
|
||||
}
|
||||
} catch (err) {
|
||||
toast(err.message);
|
||||
e.currentTarget.disabled = false;
|
||||
}
|
||||
});
|
||||
$("#refreshInc").addEventListener("click", () =>
|
||||
startJob("/api/refresh", { mode: "incremental" }, "обновление"));
|
||||
$("#refreshFull").addEventListener("click", () => {
|
||||
|
||||
@@ -105,6 +105,7 @@
|
||||
</div>
|
||||
<div class="refresh-actions">
|
||||
<button id="jobCancel" class="ghost" type="button" hidden>отменить задачу</button>
|
||||
<button id="jobRetry" class="ghost" type="button" hidden>повторить</button>
|
||||
</div>
|
||||
<div class="dp-note" id="jobStatus"></div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user