Nottybro commited on
Commit
9df8967
·
verified ·
1 Parent(s): 821ba63

Error reports service (/cos2/)

Browse files
Files changed (4) hide show
  1. Dockerfile +1 -1
  2. nginx.conf +9 -1
  3. reports.py +176 -0
  4. run.py +117 -113
Dockerfile CHANGED
@@ -11,7 +11,7 @@ RUN useradd -m -u 1000 user
11
  WORKDIR /app
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
- COPY app.py nginx.conf run.py ./
15
  COPY server/ ./server/
16
  RUN chmod +x server/CaptainServer.x86_64 && chown -R user:user /app
17
 
 
11
  WORKDIR /app
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
+ COPY app.py nginx.conf run.py reports.py ./
15
  COPY server/ ./server/
16
  RUN chmod +x server/CaptainServer.x86_64 && chown -R user:user /app
17
 
nginx.conf CHANGED
@@ -1,5 +1,6 @@
1
  # Front door on the Space's port. WebSocket upgrades are game players (Captain of Sea server on
2
- # 27777); every other request is the Kimi proxy (uvicorn on 8000), exactly as before.
 
3
  worker_processes 1;
4
  pid /tmp/nginx.pid;
5
  error_log /dev/stderr warn;
@@ -27,6 +28,13 @@ http {
27
  listen 7860;
28
  client_max_body_size 50m;
29
 
 
 
 
 
 
 
 
30
  location / {
31
  proxy_pass $backend;
32
  proxy_http_version 1.1;
 
1
  # Front door on the Space's port. WebSocket upgrades are game players (Captain of Sea server on
2
+ # 27777), /cos2/ is the game's error reports (8001); every other request is the Kimi proxy (uvicorn
3
+ # on 8000), exactly as before.
4
  worker_processes 1;
5
  pid /tmp/nginx.pid;
6
  error_log /dev/stderr warn;
 
28
  listen 7860;
29
  client_max_body_size 50m;
30
 
31
+ # The game's error reports (reports.py).
32
+ location /cos2/ {
33
+ proxy_pass http://127.0.0.1:8001;
34
+ proxy_http_version 1.1;
35
+ proxy_set_header X-Forwarded-For $http_x_forwarded_for;
36
+ }
37
+
38
  location / {
39
  proxy_pass $backend;
40
  proxy_http_version 1.1;
reports.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Captain of Sea error reports. The game posts what broke in a player's browser (Assets/Game/Scripts/
3
+ ErrorReporter.cs: no names, ids or emails), and this keeps a tally per distinct error, plus how many
4
+ sessions started and the frame rates players got, in <CAPTAIN_SAVES>/reports/errors.json (backed up
5
+ with the saves by run.py). nginx sends /cos2/ here.
6
+
7
+ POST /cos2/report one report (JSON, sent as text/plain so browsers skip the CORS preflight)
8
+ GET /cos2/errors?key=... the tally (key = the REPORT_KEY secret; off without it)
9
+ """
10
+ import json
11
+ import os
12
+ import re
13
+ import signal
14
+ import sys
15
+ import threading
16
+ import time
17
+ from collections import deque
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+ from urllib.parse import parse_qs, urlparse
20
+
21
+ PATH = os.path.join(os.environ.get("CAPTAIN_SAVES", "/home/user/saves"), "reports", "errors.json")
22
+ KEY = os.environ.get("REPORT_KEY", "")
23
+ PORT = int(os.environ.get("REPORTS_PORT", "8001"))
24
+ MAX_BODY = 8192
25
+ MAX_ERRORS = 300 # distinct errors kept
26
+ MAX_KEYS = 20 # per breakdown (gpu, browser...); the rest count as "other"
27
+ PER_IP = 60 # reports per address per 10 minutes
28
+
29
+ lock = threading.Lock()
30
+ dirty = False
31
+ recent = {} # address -> deque of times (memory only, never saved)
32
+
33
+
34
+ def today():
35
+ return time.strftime("%Y-%m-%d", time.gmtime())
36
+
37
+
38
+ def load():
39
+ try:
40
+ with open(PATH, encoding="utf-8") as f:
41
+ return json.load(f)
42
+ except Exception:
43
+ return {"since": today(), "sessions": {}, "fps": [], "errors": {}}
44
+
45
+
46
+ data = load()
47
+
48
+
49
+ def save():
50
+ global dirty
51
+ with lock:
52
+ if not dirty:
53
+ return
54
+ text = json.dumps(data, separators=(",", ":"))
55
+ dirty = False
56
+ os.makedirs(os.path.dirname(PATH), exist_ok=True)
57
+ tmp = PATH + ".tmp"
58
+ with open(tmp, "w", encoding="utf-8") as f:
59
+ f.write(text)
60
+ os.replace(tmp, PATH)
61
+
62
+
63
+ def bump(d, key, n=1):
64
+ key = str(key or "?")[:80]
65
+ if key not in d and len(d) >= MAX_KEYS:
66
+ key = "other"
67
+ d[key] = d.get(key, 0) + n
68
+
69
+
70
+ def s(r, k, n=120):
71
+ v = r.get(k)
72
+ return str(v)[:n] if v is not None else ""
73
+
74
+
75
+ def record(r):
76
+ global dirty
77
+ kind = s(r, "kind", 12)
78
+ with lock:
79
+ if kind == "hello":
80
+ day = data["sessions"].setdefault(today(), {"n": 0, "mobile": 0, "q": {}, "gpu": {}, "dev": {}, "os": {}})
81
+ day["n"] += 1
82
+ day["mobile"] += 1 if r.get("mob") else 0
83
+ for k in ("q", "gpu", "dev", "os"):
84
+ bump(day[k], s(r, k))
85
+ elif kind == "fps":
86
+ data["fps"].append({k: r.get(k) for k in ("fps", "slow", "q", "gpu", "dev", "mob", "mode", "w", "h")} | {"day": today()})
87
+ del data["fps"][:-500]
88
+ elif kind in ("error", "js"):
89
+ msg = s(r, "msg", 400)
90
+ sig = kind + ":" + re.sub(r"\d+", "#", msg)[:200]
91
+ e = data["errors"].get(sig)
92
+ if e is None:
93
+ if len(data["errors"]) >= MAX_ERRORS:
94
+ return
95
+ e = data["errors"][sig] = {"kind": kind, "type": s(r, "type", 20), "msg": msg, "stack": s(r, "stack", 1500),
96
+ "count": 0, "first": today(), "last": "", "gpu": {}, "dev": {}, "q": {}, "mode": {}, "v": {}}
97
+ e["count"] += 1
98
+ e["last"] = today()
99
+ for k in ("gpu", "dev", "q", "mode", "v"):
100
+ bump(e[k], s(r, k))
101
+ else:
102
+ return
103
+ dirty = True
104
+
105
+
106
+ class Handler(BaseHTTPRequestHandler):
107
+ def log_message(self, *_):
108
+ pass
109
+
110
+ def reply(self, code, body=b"", kind="text/plain"):
111
+ self.send_response(code)
112
+ self.send_header("Access-Control-Allow-Origin", "*")
113
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
114
+ self.send_header("Content-Type", kind)
115
+ self.send_header("Content-Length", str(len(body)))
116
+ self.end_headers()
117
+ self.wfile.write(body)
118
+
119
+ def do_OPTIONS(self):
120
+ self.reply(204)
121
+
122
+ def do_POST(self):
123
+ if urlparse(self.path).path != "/cos2/report":
124
+ return self.reply(404)
125
+ n = int(self.headers.get("Content-Length") or 0)
126
+ if n <= 0 or n > MAX_BODY:
127
+ return self.reply(413)
128
+ body = self.rfile.read(n)
129
+ who = (self.headers.get("X-Forwarded-For") or self.client_address[0]).split(",")[0].strip()
130
+ now = time.time()
131
+ with lock:
132
+ q = recent.setdefault(who, deque())
133
+ while q and now - q[0] > 600:
134
+ q.popleft()
135
+ if len(q) >= PER_IP:
136
+ return self.reply(429)
137
+ q.append(now)
138
+ if len(recent) > 5000:
139
+ recent.clear()
140
+ try:
141
+ r = json.loads(body)
142
+ if isinstance(r, dict):
143
+ record(r)
144
+ except Exception:
145
+ return self.reply(400)
146
+ self.reply(204)
147
+
148
+ def do_GET(self):
149
+ u = urlparse(self.path)
150
+ if u.path != "/cos2/errors" or not KEY or parse_qs(u.query).get("key", [""])[0] != KEY:
151
+ return self.reply(404)
152
+ with lock:
153
+ body = json.dumps(data, indent=1).encode()
154
+ self.reply(200, body, "application/json")
155
+
156
+
157
+ def saver():
158
+ while True:
159
+ time.sleep(30)
160
+ try:
161
+ save()
162
+ except Exception as e:
163
+ print("[reports] save failed: %s" % e, flush=True)
164
+
165
+
166
+ def stop(*_):
167
+ save()
168
+ sys.exit(0)
169
+
170
+
171
+ if __name__ == "__main__":
172
+ signal.signal(signal.SIGTERM, stop)
173
+ signal.signal(signal.SIGINT, stop)
174
+ threading.Thread(target=saver, daemon=True).start()
175
+ print("[reports] listening on %d (%d errors so far)" % (PORT, len(data["errors"])), flush=True)
176
+ ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
run.py CHANGED
@@ -1,113 +1,117 @@
1
- """
2
- Runs the Space: nginx in front (port 7860), the Kimi proxy (uvicorn on 8000) and the Captain of Sea
3
- server (27777), restarting either if it stops. The Space's disk is wiped on every restart, so the
4
- captains' saves are restored from a private dataset at start and backed up to it every few minutes
5
- (needs the HF_TOKEN secret; SAVES_REPO names the dataset).
6
- """
7
- import os
8
- import signal
9
- import subprocess
10
- import sys
11
- import threading
12
- import time
13
-
14
- SAVES = os.environ.get("CAPTAIN_SAVES", "/home/user/saves")
15
- REPO = os.environ.get("SAVES_REPO", "Nottybro/captain-of-sea-saves")
16
- TOKEN = os.environ.get("HF_TOKEN")
17
- BACKUP_EVERY = int(os.environ.get("BACKUP_SECONDS", "300"))
18
-
19
- GAME = ["./server/CaptainServer.x86_64", "-batchmode", "-nographics", "-logFile", "-"]
20
- PROXY = [sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", "8000"]
21
-
22
- stopping = threading.Event()
23
- uploaded = {} # file name -> mtime last backed up
24
-
25
-
26
- def log(msg):
27
- print("[run] " + msg, flush=True)
28
-
29
-
30
- def restore():
31
- os.makedirs(SAVES, exist_ok=True)
32
- if not TOKEN:
33
- log("no HF_TOKEN secret: saves won't outlive a restart")
34
- return
35
- from huggingface_hub import HfApi, snapshot_download
36
- try:
37
- HfApi(token=TOKEN).create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
38
- snapshot_download(REPO, repo_type="dataset", local_dir=SAVES, token=TOKEN, allow_patterns="*.json")
39
- except Exception as e:
40
- log("restore failed: %s" % e)
41
- for f in os.listdir(SAVES):
42
- if f.endswith(".json"):
43
- uploaded[f] = os.path.getmtime(os.path.join(SAVES, f))
44
- log("restored %d captains" % len(uploaded))
45
-
46
-
47
- def backup():
48
- if not TOKEN:
49
- return
50
- from huggingface_hub import CommitOperationAdd, HfApi
51
- changed = []
52
- for f in os.listdir(SAVES):
53
- p = os.path.join(SAVES, f)
54
- if f.endswith(".json") and uploaded.get(f) != os.path.getmtime(p):
55
- changed.append((f, os.path.getmtime(p)))
56
- if not changed:
57
- return
58
- try:
59
- ops = [CommitOperationAdd(path_in_repo=f, path_or_fileobj=os.path.join(SAVES, f)) for f, _ in changed]
60
- HfApi(token=TOKEN).create_commit(REPO, repo_type="dataset", operations=ops, commit_message="%d captains" % len(ops))
61
- for f, m in changed:
62
- uploaded[f] = m
63
- log("backed up %d captains" % len(changed))
64
- except Exception as e:
65
- log("backup failed: %s" % e)
66
-
67
-
68
- def backups():
69
- while not stopping.wait(BACKUP_EVERY):
70
- backup()
71
-
72
-
73
- def keep_running(name, cmd, cwd="/app"):
74
- """Start cmd and start it again whenever it stops (until the Space shuts down)."""
75
- def loop():
76
- while not stopping.is_set():
77
- log("starting " + name)
78
- p = subprocess.Popen(cmd, cwd=cwd)
79
- procs[name] = p
80
- p.wait()
81
- if stopping.is_set():
82
- return
83
- log("%s stopped (code %s), restarting in 3 s" % (name, p.returncode))
84
- time.sleep(3)
85
- threading.Thread(target=loop, daemon=True).start()
86
-
87
-
88
- procs = {}
89
-
90
-
91
- def shutdown(*_):
92
- log("shutting down")
93
- stopping.set()
94
- for p in procs.values():
95
- if p.poll() is None:
96
- p.send_signal(signal.SIGTERM)
97
- time.sleep(4) # the game saves everyone on the way down
98
- backup()
99
- sys.exit(0)
100
-
101
-
102
- if __name__ == "__main__":
103
- signal.signal(signal.SIGTERM, shutdown)
104
- signal.signal(signal.SIGINT, shutdown)
105
- restore()
106
- keep_running("proxy", PROXY)
107
- keep_running("game", GAME)
108
- threading.Thread(target=backups, daemon=True).start()
109
- nginx = subprocess.Popen(["nginx", "-c", "/app/nginx.conf", "-g", "daemon off;"])
110
- procs["nginx"] = nginx
111
- nginx.wait()
112
- log("nginx stopped (code %s)" % nginx.returncode)
113
- shutdown()
 
 
 
 
 
1
+ """
2
+ Runs the Space: nginx in front (port 7860), the Kimi proxy (uvicorn on 8000) and the Captain of Sea
3
+ server (27777), restarting either if it stops. The Space's disk is wiped on every restart, so the
4
+ captains' saves are restored from a private dataset at start and backed up to it every few minutes
5
+ (needs the HF_TOKEN secret; SAVES_REPO names the dataset), along with the game's error reports
6
+ (reports.py, reports/errors.json).
7
+ """
8
+ import os
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ import threading
13
+ import time
14
+
15
+ SAVES = os.environ.get("CAPTAIN_SAVES", "/home/user/saves")
16
+ REPO = os.environ.get("SAVES_REPO", "Nottybro/captain-of-sea-saves")
17
+ TOKEN = os.environ.get("HF_TOKEN")
18
+ BACKUP_EVERY = int(os.environ.get("BACKUP_SECONDS", "300"))
19
+
20
+ GAME = ["./server/CaptainServer.x86_64", "-batchmode", "-nographics", "-logFile", "-"]
21
+ PROXY = [sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", "8000"]
22
+ REPORTS = [sys.executable, "-u", "reports.py"]
23
+ REPORT_FILE = "reports/errors.json"
24
+
25
+ stopping = threading.Event()
26
+ uploaded = {} # file name -> mtime last backed up
27
+
28
+
29
+ def log(msg):
30
+ print("[run] " + msg, flush=True)
31
+
32
+
33
+ def restore():
34
+ os.makedirs(SAVES, exist_ok=True)
35
+ if not TOKEN:
36
+ log("no HF_TOKEN secret: saves won't outlive a restart")
37
+ return
38
+ from huggingface_hub import HfApi, snapshot_download
39
+ try:
40
+ HfApi(token=TOKEN).create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
41
+ snapshot_download(REPO, repo_type="dataset", local_dir=SAVES, token=TOKEN, allow_patterns=["*.json", REPORT_FILE])
42
+ except Exception as e:
43
+ log("restore failed: %s" % e)
44
+ for f in os.listdir(SAVES):
45
+ if f.endswith(".json"):
46
+ uploaded[f] = os.path.getmtime(os.path.join(SAVES, f))
47
+ log("restored %d captains" % len(uploaded))
48
+
49
+
50
+ def backup():
51
+ if not TOKEN:
52
+ return
53
+ from huggingface_hub import CommitOperationAdd, HfApi
54
+ changed = []
55
+ for f in os.listdir(SAVES) + [REPORT_FILE]:
56
+ p = os.path.join(SAVES, f)
57
+ if f.endswith(".json") and os.path.isfile(p) and uploaded.get(f) != os.path.getmtime(p):
58
+ changed.append((f, os.path.getmtime(p)))
59
+ if not changed:
60
+ return
61
+ try:
62
+ ops = [CommitOperationAdd(path_in_repo=f, path_or_fileobj=os.path.join(SAVES, f)) for f, _ in changed]
63
+ HfApi(token=TOKEN).create_commit(REPO, repo_type="dataset", operations=ops, commit_message="%d captains" % len(ops))
64
+ for f, m in changed:
65
+ uploaded[f] = m
66
+ log("backed up %d captains" % len(changed))
67
+ except Exception as e:
68
+ log("backup failed: %s" % e)
69
+
70
+
71
+ def backups():
72
+ while not stopping.wait(BACKUP_EVERY):
73
+ backup()
74
+
75
+
76
+ def keep_running(name, cmd, cwd="/app"):
77
+ """Start cmd and start it again whenever it stops (until the Space shuts down)."""
78
+ def loop():
79
+ while not stopping.is_set():
80
+ log("starting " + name)
81
+ p = subprocess.Popen(cmd, cwd=cwd)
82
+ procs[name] = p
83
+ p.wait()
84
+ if stopping.is_set():
85
+ return
86
+ log("%s stopped (code %s), restarting in 3 s" % (name, p.returncode))
87
+ time.sleep(3)
88
+ threading.Thread(target=loop, daemon=True).start()
89
+
90
+
91
+ procs = {}
92
+
93
+
94
+ def shutdown(*_):
95
+ log("shutting down")
96
+ stopping.set()
97
+ for p in procs.values():
98
+ if p.poll() is None:
99
+ p.send_signal(signal.SIGTERM)
100
+ time.sleep(4) # the game saves everyone on the way down
101
+ backup()
102
+ sys.exit(0)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ signal.signal(signal.SIGTERM, shutdown)
107
+ signal.signal(signal.SIGINT, shutdown)
108
+ restore()
109
+ keep_running("proxy", PROXY)
110
+ keep_running("game", GAME)
111
+ keep_running("reports", REPORTS)
112
+ threading.Thread(target=backups, daemon=True).start()
113
+ nginx = subprocess.Popen(["nginx", "-c", "/app/nginx.conf", "-g", "daemon off;"])
114
+ procs["nginx"] = nginx
115
+ nginx.wait()
116
+ log("nginx stopped (code %s)" % nginx.returncode)
117
+ shutdown()