Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
210 lines (175 loc) · 7.96 KB
/
Copy pathserver.py
File metadata and controls
210 lines (175 loc) · 7.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""
server.py — WebSocket + HTTP server for the live dashboard
Transport properties that matter for a live demo:
* REPLAY — a bounded ring buffer of every event; each newly connected
client first receives the buffered history, so opening the browser at any
moment (even mid-run or after a reconnect) shows the full picture.
* START-ON-VIEW — the arena does not begin until the first WebSocket
client connects, so the presenter opens the dashboard, THEN the run
happens live in front of them. (srv.start_arena() can trigger it early.)
* CLEAN SHUTDOWN — cross-thread delivery uses loop.call_soon_threadsafe
onto asyncio.Queues; no executor threads ever block on queue.get.
* TRUE BROADCAST — every client gets every event (per-client queues).
* Path-traversal guard on the static file handler.
"""
from __future__ import annotations
import argparse
import asyncio
import collections
import json
import mimetypes
import queue
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, Optional, Set
_clients: Dict[Any, Dict[str, Any]] = {} # ws -> {"q": asyncio.Queue, "loop": Loop}
_registry_lock = threading.Lock()
_replay: collections.deque = collections.deque(maxlen=5000)
_start_signal = threading.Event()
MAX_QUEUE = 4000
def start_arena() -> None:
"""Unblock the arena thread (called automatically on first client)."""
_start_signal.set()
def _push(q: asyncio.Queue, msg: str) -> None:
if q.full():
try:
q.get_nowait() # drop oldest
except asyncio.QueueEmpty:
pass
try:
q.put_nowait(msg)
except asyncio.QueueFull:
pass
def _fan_out(data: Dict) -> None:
"""Arena thread → replay buffer + every connected client."""
msg = json.dumps(data)
_replay.append(msg)
with _registry_lock:
targets = [(c["q"], c["loop"]) for c in _clients.values()]
for q, loop in targets:
try:
loop.call_soon_threadsafe(_push, q, msg)
except RuntimeError:
pass # loop already closed
# ──────────────────────────────────────────────
# Arena thread
# ──────────────────────────────────────────────
def _run_arena(attacker_mode: str, max_epochs: int, minimax_depth: int,
rounds_per_epoch: int, seed,
spoof_rate: float, enable_auth: bool,
enforce_data_integrity: bool = False) -> None:
from engine.coevolution import CoevolutionEngine
_start_signal.wait() # demo: run begins when the first viewer connects
engine = CoevolutionEngine(
attacker_mode=attacker_mode,
rounds_per_epoch=rounds_per_epoch,
max_epochs=max_epochs,
minimax_depth=minimax_depth,
seed=seed,
broadcast_fn=_fan_out,
enable_auth=enable_auth,
spoof_rate=spoof_rate,
enforce_data_integrity=enforce_data_integrity,
)
_fan_out({"type": "arena_start", "attacker_mode": attacker_mode,
"max_epochs": max_epochs})
engine.run()
# ──────────────────────────────────────────────
# WebSocket handler
# ──────────────────────────────────────────────
async def _ws_handler(websocket) -> None:
q: asyncio.Queue = asyncio.Queue(maxsize=MAX_QUEUE)
loop = asyncio.get_running_loop()
# Register + deliver replay snapshot atomically (no gap between the two).
with _registry_lock:
_clients[websocket] = {"q": q, "loop": loop}
snapshot = list(_replay)
if len(_clients) == 1:
start_arena()
for msg in snapshot:
_push(q, msg)
sender = asyncio.create_task(_sender(websocket, q))
try:
async for _ in websocket: # keepalive; ignore client messages
pass
except Exception:
pass
finally:
sender.cancel()
with _registry_lock:
_clients.pop(websocket, None)
async def _sender(websocket, q: asyncio.Queue) -> None:
try:
while True:
msg = await q.get()
await websocket.send(msg)
except Exception:
pass
# ──────────────────────────────────────────────
# HTTP handler (serves dashboard/)
# ──────────────────────────────────────────────
DASHBOARD_DIR = Path(__file__).parent / "dashboard"
class _HTTPHandler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass # silence
def do_GET(self):
path = self.path.lstrip("/") or "index.html"
file_path = (DASHBOARD_DIR / path).resolve()
if not str(file_path).startswith(str(DASHBOARD_DIR.resolve())) or not file_path.is_file():
self.send_error(404)
return
mime, _ = mimetypes.guess_type(str(file_path))
self.send_response(200)
self.send_header("Content-Type", mime or "text/plain")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(file_path.read_bytes())
def _run_http(port: int) -> None:
server = ThreadingHTTPServer(("localhost", port), _HTTPHandler)
server.serve_forever()
async def _ws_serve(port: int) -> None:
import websockets
async with websockets.serve(_ws_handler, "localhost", port):
print(f" WebSocket: ws://localhost:{port}")
await asyncio.Future() # run forever
def serve(port: int = 8765, attacker: str = "random", epochs: int = 50,
depth: int = 3, rounds: int = 5, seed=None,
spoof_rate: float = 0.0, enable_auth: bool = True,
enforce_data_integrity: bool = False) -> None:
http_port = port + 1 # e.g. 8766 for HTTP, 8765 for WS
print("\n Self-Modifying Runtime Dashboard")
print(" ----------------------------------")
print(f" Dashboard: http://localhost:{http_port}")
print(f" WebSocket: ws://localhost:{port}")
print(f" Attacker: {attacker} Epochs: {epochs} Seed: {seed}")
print(f" Spoof rate: {spoof_rate} Auth: {'ON' if enable_auth else 'OFF'}"
f" Schema: {'ON' if enforce_data_integrity else 'OFF'}")
print(" The run starts when the first browser connects.\n")
threading.Thread(target=_run_http, args=(http_port,), daemon=True).start()
threading.Thread(
target=_run_arena,
args=(attacker, epochs, depth, rounds, seed, spoof_rate, enable_auth,
enforce_data_integrity),
daemon=True,
).start();
asyncio.run(_ws_serve(port))
def main() -> None:
parser = argparse.ArgumentParser(description="Self-Modifying Runtime - Dashboard Server")
parser.add_argument("--port", type=int, default=8765)
parser.add_argument("--attacker", type=str, default="random",
choices=["random", "search", "rl", "oracle"])
parser.add_argument("--epochs", type=int, default=50)
parser.add_argument("--depth", type=int, default=3)
parser.add_argument("--rounds", type=int, default=5)
parser.add_argument("--seed", type=int, default=None)
parser.add_argument("--spoof", type=float, default=0.0)
parser.add_argument("--schema", action="store_true")
parser.add_argument("--no-auth", dest="enable_auth", action="store_false")
args = parser.parse_args()
serve(port=args.port, attacker=args.attacker, epochs=args.epochs,
depth=args.depth, rounds=args.rounds, seed=args.seed,
spoof_rate=args.spoof, enable_auth=args.enable_auth,
enforce_data_integrity=args.schema)
if __name__ == "__main__":
main()