Files
SteamBase/tools/upload_snapshot.py
strsv ffe9e76a5b
CI / test (push) Successful in 40s
feat: export and upload library snapshots
Add snapshot.zip export with manifest/catalog/library, deterministic checksum, --no-notes/--include-dlc, plus an upload client with idempotency, token config and import polling.
2026-11-07 07:09:29 +03:00

216 lines
8.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Export and upload a SteamBase snapshot to SteamBaseServer.
python tools/upload_snapshot.py --url https://steambase.strsv.ru --token ...
python tools/upload_snapshot.py --file snapshot.zip
Configuration precedence: CLI > environment > data/server.json.
The token is never printed or written to logs.
Environment:
STEAMBASE_SERVER_URL
STEAMBASE_UPLOAD_TOKEN
STEAMBASE_SERVER_HANDLE
"""
import argparse
import json
import os
import sys
import tempfile
import time
import urllib.error
import urllib.request
import uuid
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8")
except Exception:
pass
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import db
import export_snapshot as exporter
CONFIG_FILE = os.path.join(BASE_DIR, "data", "server.json")
DEFAULT_TIMEOUT = 60
DEFAULT_POLL_INTERVAL = 2
DEFAULT_POLL_TIMEOUT = 300
class UploadError(RuntimeError):
def __init__(self, message, status=None, code=None):
super().__init__(message)
self.status = status
self.code = code
def load_config(path=CONFIG_FILE):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def resolve_config(url=None, token=None, handle=None, path=CONFIG_FILE):
saved = load_config(path)
url = (url or os.environ.get("STEAMBASE_SERVER_URL") or saved.get("url") or "").strip()
token = (token or os.environ.get("STEAMBASE_UPLOAD_TOKEN") or saved.get("token") or "").strip()
handle = (handle or os.environ.get("STEAMBASE_SERVER_HANDLE") or saved.get("handle") or "").strip()
return {"url": url.rstrip("/"), "token": token, "handle": handle}
def _request(url, token, data=None, headers=None, timeout=DEFAULT_TIMEOUT):
request_headers = {"Authorization": f"Bearer {token}"}
request_headers.update(headers or {})
request = urllib.request.Request(url, data=data, headers=request_headers,
method="POST" if data is not None else "GET")
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", "replace")
try:
payload = json.loads(body)
error = payload.get("error") or {}
message = error.get("message") or body or f"HTTP {exc.code}"
code = error.get("code")
except ValueError:
message = body or f"HTTP {exc.code}"
code = None
if exc.code == 401:
message = "токен неверный или отозван"
elif exc.code == 403:
message = "нет прав на загрузку"
elif exc.code == 413:
message = "снимок больше лимита сервера"
elif exc.code == 429:
message = "слишком частые загрузки, попробуйте позже"
raise UploadError(message, status=exc.code, code=code) from None
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise UploadError(f"ошибка соединения: {type(exc).__name__}") from None
def upload(url, token, path, timeout=DEFAULT_TIMEOUT, idempotency_key=None):
if not url:
raise UploadError("не задан URL сервера")
if not token:
raise UploadError("не задан upload-токен")
with open(path, "rb") as handle:
body = handle.read()
checksum = exporter.snapshot_checksum(path)
headers = {
"Content-Type": "application/zip",
"X-Snapshot-Checksum": f"sha256={checksum}",
"Idempotency-Key": idempotency_key or str(uuid.uuid4()),
}
data = _request(f"{url.rstrip('/')}/api/v1/snapshots", token, body, headers, timeout)
snapshot = data.get("snapshot") or data
if not isinstance(snapshot, dict) or not snapshot.get("id"):
raise UploadError("сервер вернул неожиданный ответ")
return snapshot
def status(url, token, snapshot_id, timeout=DEFAULT_TIMEOUT):
data = _request(f"{url.rstrip('/')}/api/v1/snapshots/{snapshot_id}", token, timeout=timeout)
return data.get("snapshot") or data
def wait(url, token, snapshot_id, interval=DEFAULT_POLL_INTERVAL,
timeout=DEFAULT_POLL_TIMEOUT, on_status=None):
deadline = time.time() + timeout
while True:
data = status(url, token, snapshot_id)
state = data.get("status")
if on_status:
on_status(data)
if state in ("done", "failed", "cancelled"):
return data
if time.time() >= deadline:
raise UploadError(f"импорт не завершился за {timeout} с")
time.sleep(interval)
def _print_status(data):
state = data.get("status") or "?"
counts = data.get("counts") or {}
suffix = ""
if counts:
suffix = f" | catalog={counts.get('catalog', '?')} library={counts.get('library', '?')}"
print(f" snapshot {data.get('id', '?')}: {state}{suffix}")
def main():
ap = argparse.ArgumentParser(description="Upload a SteamBase snapshot")
ap.add_argument("--url", help="server URL, e.g. https://steambase.strsv.ru")
ap.add_argument("--token", help="upload token")
ap.add_argument("--handle", help="server handle for the manifest")
ap.add_argument("--file", help="existing snapshot.zip (otherwise export now)")
ap.add_argument("--db", default=db.DEFAULT_DB)
ap.add_argument("--no-notes", action="store_true")
ap.add_argument("--no-translations", action="store_true")
ap.add_argument("--include-dlc", action="store_true")
ap.add_argument("--mode", choices=("replace", "merge"), default="replace")
ap.add_argument("--no-poll", action="store_true")
ap.add_argument("--timeout", type=float, default=DEFAULT_POLL_TIMEOUT)
args = ap.parse_args()
config = resolve_config(args.url, args.token, args.handle)
if not config["url"] or not config["token"]:
print("Задайте --url и --token (или data/server.json / env)", file=sys.stderr)
return 2
temp_dir = None
path = args.file
try:
if not path:
temp_dir = tempfile.TemporaryDirectory(prefix="steambase-snapshot-")
path = os.path.join(temp_dir.name, "snapshot.zip")
con = db.connect(args.db)
try:
manifest = exporter.write_snapshot(
con, path,
handle=config["handle"],
notes=not args.no_notes,
translations=not args.no_translations,
include_dlc=args.include_dlc,
mode=args.mode,
)
finally:
con.close()
print(f"Экспортировано: catalog={manifest['counts']['catalog']} "
f"library={manifest['counts']['library']} "
f"({os.path.getsize(path)} байт)")
snapshot = upload(config["url"], config["token"], path)
print(f"Загружено: snapshot={snapshot['id']} status={snapshot.get('status')}")
if args.no_poll:
return 0
if snapshot.get("status") in ("done", "failed", "cancelled"):
_print_status(snapshot)
return 0 if snapshot.get("status") == "done" else 1
final = wait(config["url"], config["token"], snapshot["id"],
timeout=args.timeout, on_status=None)
_print_status(final)
if final.get("status") == "done":
print("Импорт завершён")
return 0
print(f"Импорт завершился со статусом: {final.get('status')}", file=sys.stderr)
if final.get("error"):
print(final["error"], file=sys.stderr)
return 1
except UploadError as exc:
print(f"Ошибка: {exc}", file=sys.stderr)
return 1
finally:
if temp_dir is not None:
temp_dir.cleanup()
if __name__ == "__main__":
raise SystemExit(main())